D T
D T

Reputation: 3746

Does JavaScript support formatting numbers by string format?

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?

Upvotes: 5

Views: 126

Answers (6)

palaѕн
palaѕн

Reputation: 73906

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

Upvotes: 5

Code Maniac
Code Maniac

Reputation: 37755

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

Upvotes: 0

ROOT
ROOT

Reputation: 11622

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>

Upvotes: 1

sourav satyam
sourav satyam

Reputation: 986

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

let num = 1234567.8333
console.log(parseFloat(num.toFixed(2)).toLocaleString())

Upvotes: 0

Alex - Tin Le
Alex - Tin Le

Reputation: 2000

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

enter image description here

Upvotes: 3

Nilanka Manoj
Nilanka Manoj

Reputation: 3718

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.

Upvotes: 0

Related Questions