Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript support formatting numbers by string format?

Tags:

javascript

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?

like image 326
D T Avatar asked Mar 17 '20 12:03

D T


People also ask

How do you format a number in JavaScript?

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.

How to convert a number to a string in JavaScript?

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.

Can JavaScript strings have numeric content?

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:

What is the numberformat object in JavaScript?

The Intl.NumberFormat object is a constructor for objects that enable language sensitive number formatting. JavaScript Demo: Intl.NumberFormat.


Video Answer


2 Answers

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
like image 163
palaѕн Avatar answered Sep 24 '22 07:09

palaѕн


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

enter image description here

like image 23
Alex - Tin Le Avatar answered Sep 24 '22 07:09

Alex - Tin Le