Format number to always show 2 decimal places

2018-12-31 03:15发布

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.

26条回答
余生无你
2楼-- · 2018-12-31 03:21
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

document.getElementById('line1').innerHTML = Number(1).toFixed(2);
document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);
document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);
document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
<span id="line1"></span>
<br/>
<span id="line2"></span>
<br/>
<span id="line3"></span>
<br/>
<span id="line4"></span>

查看更多
君临天下
3楼-- · 2018-12-31 03:23

Simplest answer:

var num = 1.2353453;
num.toFixed(2); // 1.24

Example: http://jsfiddle.net/E2XU7/

查看更多
初与友歌
4楼-- · 2018-12-31 03:23
function currencyFormat (num) {
    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

console.info(currencyFormat(2665));   // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00
查看更多
若你有天会懂
5楼-- · 2018-12-31 03:24
var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);
查看更多
皆成旧梦
6楼-- · 2018-12-31 03:25

parseInt(number * 100) / 100; worked for me.

查看更多
唯独是你
7楼-- · 2018-12-31 03:28

Convert a number into a string, keeping only two decimals:

var num = 5.56789;
var n = num.toFixed(2);

The result of n will be:

5.57
查看更多
登录 后发表回答