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?
JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed () method to format the number with decimal points, and the toLocaleString () method to format the number with commas and Intl.NumberFormat () method to format the number with currency.
Or you could use the sugar.js library, and the format method: format ( place = 0 , thousands = ',' , decimal = '.' ) Formats the number to a readable string. If place is undefined, will automatically determine the place. thousands is the character used for the thousands separator. decimal is the character used for the decimal point.
JavaScript strings can have numeric content: let x = 100; // x is a number let y = "100"; // y is a string JavaScript will try to convert strings to numbers in all numeric operations:
The Intl.NumberFormat object is a constructor for objects that enable language sensitive number formatting. JavaScript Demo: Intl.NumberFormat.
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
If you want more complex formatting. You can have a look at http://numeraljs.com/#format
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With