嗨,大家好,我想将数字四舍五入到小数点后两位。我将举一个例子和我尝试过的。
可以说我有15.07567,要进行四舍五入,我做到了:
price = Math.round(15.07567 * 100) / 100;
//得到15.08
但是,如果我们有以0结尾的数字(例如15.10),并且我们想要两个小数,这将带来一个问题。
price = Math.round(15.10 * 100) / 100;
//15.1
嗯,所以我尝试使用toFixed()
price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
//我得到“ 15.10”,这很好,但是它返回一个字符串,以后可能会给我带来问题,因此我尝试使用以下方法解决此问题:
price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
Number(total) //or parseFloat(total)
//我得到15.1,然后绕行了吗?
正如乔丹所说。当JavaScript显示数字时,它将删除0。我只是按原样存储该值,当您显示该值时,请通过.toFixed(2)运行该值,以使其正确显示。甚至更好的是,找到一种货币格式化程序,因为这似乎是您要在视图侧显示和使用的格式。
这是一个不错的货币格式化脚本。
Number.prototype.formatMoney = function(c, d='.', t=','){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
然后,可以通过以下代码将其用于面向对象的方式:
price.formatMoney(2);
或者,如果要为欧洲指定千位和十进制分隔符。
price.formatMoney(2, ',', '.');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句