【发布时间】:2012-10-01 01:32:39
【问题描述】:
我正在使用 javascript round 对数字进行四舍五入。但是当值为$106.70 时,输出仅显示$106.7 并且缺少最后一个0。如何为以零结尾的数字添加零,或者有没有比使用 if else 更简单的方法来检查这个?
【问题讨论】:
标签: javascript numbers rounding
我正在使用 javascript round 对数字进行四舍五入。但是当值为$106.70 时,输出仅显示$106.7 并且缺少最后一个0。如何为以零结尾的数字添加零,或者有没有比使用 if else 更简单的方法来检查这个?
【问题讨论】:
标签: javascript numbers rounding
您可以使用.toFixed 方法:
var n = 106.72; console.log(n.toFixed(2)); //=> '106.72'
var n = 106.70; console.log(n.toFixed(2)); //=> '106.70'
var n = 106.7; console.log(n.toFixed(2)); //=> '106.70'
var n = 106; console.log(n.toFixed(2)); //=> '106.00'
它会四舍五入:
var n = 106.76; console.log(n.toFixed(1)); //=> '106.8'
【讨论】: