# 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.

## 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.

## 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
``````

## 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)

## 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:

``````var num = new Number(14.12);