5

In .NET I can format number by this code:

Dim num = 1234567.8933
Dim res = num.ToString("#,##0.00")

Result: res= 1,234,567.89

I want using this format "#,##0.00" in JavaScript. Does it support formatting numbers by string format?

Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
D T
  • 2,998
  • 7
  • 37
  • 76
  • 1
    Not built in, at least not like this. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat – Felix Kling Mar 17 '20 at 12:16
  • [Format numbers in JavaScript similar to C#](https://stackoverflow.com/questions/1068284/format-numbers-in-javascript-similar-to-c-sharp) – Andreas Mar 17 '20 at 12:21

6 Answers6

5

Does it support formatting numbers by string format?

We don't have built-in support to format numbers, but we have few options to get desired #,##0.00 format like:

Using .toLocaleString():

const num = 1234567.8933

// To get only two decimal places use maximumFractionDigits option
const options = {minimumFractionDigits: 2, maximumFractionDigits: 2}
const res = num.toLocaleString(undefined, options)
console.log(res)   //=> 1,234,567.89

Using Intl.NumberFormat:

const num = 1234567.8933

// To get only two decimal places use maximumFractionDigits option
const options = {minimumFractionDigits: 2, maximumFractionDigits: 2}
const res = new Intl.NumberFormat(undefined, options).format(num)
console.log(res)   //=> 1,234,567.89
palaѕн
  • 68,816
  • 17
  • 108
  • 129
3

If you want more complex formatting. You can have a look at http://numeraljs.com/#format

enter image description here

Alex - Tin Le
  • 1,917
  • 1
  • 5
  • 11
1

As mentioned in the comments, not out of the box maybe numeral.js would help:

var num = numeral(1234567.8933).format('0,0,0.00');
console.log(num)
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
ROOT
  • 10,813
  • 5
  • 29
  • 43
0

You can use Intl.NumberFormat

let num = 1234567.8933

let value = new Intl.NumberFormat('en-US', {maximumFractionDigits: 2}).format(num);

console.log(value)

Intl.NumberFormat

Code Maniac
  • 35,187
  • 4
  • 31
  • 54
0

You can use a regular expression to format :

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Change expression as you required. It addresses the dynamic formatting issue.

Nilanka Manoj
  • 3,358
  • 3
  • 13
  • 43
0

Here fixed upto 2 digit after decimal and use toLocaleString()

let num = 1234567.8333
console.log(parseFloat(num.toFixed(2)).toLocaleString())
sourav satyam
  • 900
  • 3
  • 10