Format number to always show 2 decimal places

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

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

I have been using this:

parseFloat(num).toFixed(2);

But it's displaying 1 as 1 , rather than 1.00 .


This works fine in FF4:

parseFloat(Math.round(num3 * 100) / 100).toFixed(2);

Live Demo

var num1 = "1";
document.getElementById('num1').innerHTML = parseFloat(Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
document.getElementById('num2').innerHTML = parseFloat(Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
document.getElementById('num3').innerHTML = parseFloat(Math.round(num3 * 100) / 100).toFixed(2);
span {
    border: 1px solid #000;
    margin: 5px;
    padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>

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

This answer will fail if value = 1.005 .

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').toFixed(2); // 1.01

Credit: Rounding Decimals in JavaScript

链接地址: http://www.djcxy.com/p/13556.html

上一篇: 如何获得自从JavaScript中的unix时代以毫秒为单位的时间?

下一篇: 格式编号始终显示2位小数