Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numbers into comma separated format with two decimals in javascript

I am trying to convert numbers into comma separated format with two decimal places for each and every number in javascript:

My code:

Number(parseFloat(n).toFixed(2)).toLocaleString('en');

This code doesn't show two decimal places (.00) for whole numbers.

I am expecting following results for a set of numbers:

10000 => 100,00.00
123233.12 => 123,233.12
300000.5  => 300,000.50

Appreciate your answer, thanks.

like image 643
SatAj Avatar asked Jul 19 '16 15:07

SatAj


People also ask

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you move a number to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you round off 2 decimal places in jQuery?

To round off decimal values using jQuery, we can use the built-in JavaScript methods toFixed() or toPrecision(). The toFixed() method converts a number into a string, keeping a specified number of decimals. The toPrecision() method formats a number to a specified length.

How do you print a number with commas as thousands separators in JavaScript?

Artturi Jalli. To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.


1 Answers

You can use the minimumFractionDigits option of the toLocaleString function.

// result 3,000.00
Number(parseFloat(3000).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

// result 123,233.12
Number(parseFloat(123233.12).toFixed(2)).toLocaleString('en', {
    minimumFractionDigits: 2
});

You can even remove the parseFloat,toFixed and Number function usage as well, if this is not used for some logic other than displaying the decimal value up to 2 digits.

like image 53
Deep Avatar answered Sep 21 '22 17:09

Deep