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?

2

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

4 Comments

This might produce the requested output, but doesn't answer the question of OP.
Thank you, but my format is not fix. it can change by setting.
You can use maximumFractionDigits option to limit the fractions
Thank you , but numeral.js can support change format by my setting.
3

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

enter image description here

Comments

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>

Comments

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.

Comments

0

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.