将数字四舍五入到小数点后两位

Rounding number to two decimal places

本文关键字:两位 数字 四舍五入 小数点      更新时间:2023-09-26

嗨,伙计们,我有一个例子,a想把数字四舍五入到小数点后两位。我将举一个例子和我所尝试的。

比方说我有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,然后绕圈子走?

正如Jordan所说。当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, ',', '.');

如果你想在右边显示0,你需要在String中表示数字。。。

始终保留您的数字,当您显示它们时,将它们运行到Fixed以获得所需的显示格式,因此您将获得字符串格式的就绪值。由于该方法是必需的,因此是为显示目的而设计的,因此该函数返回一个就绪字符串,而不是数字。