大家好, 我有一个案例,想要将数字四舍五入到小数点后两位。我将举一个例子以及我的尝试。
假设我有 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) 运行它,以便它正确显示。或者更好的是,找到一个货币格式化程序,因为这似乎就是您想要在 View 端显示和使用的内容。
这是一个很好的货币格式化脚本。
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, ',', '.');
关于javascript - 将数字四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287781/