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,687
  • 7
  • 53
  • 122
D T
  • 3,522
  • 7
  • 45
  • 89
  • 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ѕн
  • 72,112
  • 17
  • 116
  • 136
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,982
  • 1
  • 6
  • 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
  • 11,363
  • 5
  • 30
  • 45
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
  • 37,143
  • 5
  • 39
  • 60
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,527
  • 4
  • 17
  • 48
0

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

let num = 1234567.8333
console.log(parseFloat(num.toFixed(2)).toLocaleString())
sourav satyam
  • 980
  • 5
  • 11