Coder Perfect

Always show two decimal places when formatting a number

Problem

I’d like to format my numbers so that they always display two decimal places, with rounding when necessary.

Examples:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

This is what I’ve been doing:

parseFloat(num).toFixed(2);

However, instead of 1.00, it displays 1 as 1.

Asked by Varada

Solution #1

(Math.round(num * 100) / 100).toFixed(2);

Live Demo

It should be noted that it will round to two decimal places, so 1.346 will yield 1.35.

Answered by drudge

Solution #2

Number(1).toFixed(2);         // 1.00
Number(1.341).toFixed(2);     // 1.34
Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35

Answered by Abel ANEIROS

Solution #3

If value = 1.005, this response will be incorrect.

As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

Cleaner code, as proposed by @Kon and the author of the original:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

You can use toFixed() at the end to keep the decimal point, e.g. 1.00, but it will return as a string.

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

Rounding Decimals with JavaScript (Credit)

Answered by razu

Solution #4

Use toLocaleString: for recent browsers.

var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });

To control the decimal separator, specify a locale tag as the first parameter. Use the following example for a dot: English U.S. locale:

num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

which gives:

The comma is used as a decimal separator in most European countries, therefore if you select Swedish/Sweden locale:

num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

it will give:

Answered by holmis83

Solution #5

var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120

Answered by Tiberiu Petcu

Post is based on https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places