将数字四舍五入到小数点后两位 [英] Rounding number to two decimal places

查看:196
本文介绍了将数字四舍五入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,想将数字四舍五入到小数点后两位.我将举一个例子和我尝试过的东西.

Hy guys, I have a case where a want to round the number to exactly two decimal places. I will give an example and what I tried.

让我们说我有15.07567可以进行总结:

Lets say I have 15.07567 To round it up I did:

price = Math.round(15.07567 * 100) / 100;

//我得到15.08

// and I get 15.08

但是,如果我们有以0结尾的数字(例如15.10),并且我们想要两个小数,就会出现问题.

But this presents a problems if we have digits that end wit 0 (example 15.10) and we want two decimals.

price = Math.round(15.10 * 100) / 100;

//15.1

嗯,所以我尝试使用toFixed()

Hmmm, so I tried to use toFixed()

price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);

//我得到"15.10",这很好,但是它返回一个字符串,以后可能会给我带来一个问题,所以我尝试使用以下方法解决此问题:

// I get "15.10", that's good but it returns a string and that could present a problem later on for me so I tried to fix this with:

price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
Number(total)  //or  parseFloat(total)

//我得到15.1,我转了一圈吗?

// I get 15.1 and around in circle I go?

推荐答案

如乔丹所说.当JavaScript显示数字时,它将删除0.我只是按原样存储该值,当您显示该值时,请通过.toFixed(2)运行该值,以使其正确显示.甚至更好的是,找到一种货币格式化程序,因为这似乎是您要在视图侧显示和使用的格式.

As Jordan said. When JavaScript displays the number it'll drop the 0. I'd just store the value as is and when you display it, run it through the .toFixed(2) so that it displays properly. Or even better, find a currency formatter since that seems to be what you're looking to display and use that on the view side.

这是一个很好的货币格式化脚本.

Here's a nice currency formating script.

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) : "");
};

然后您可以通过以下代码将其用于面向对象的方式:

Then you can use it an object oriented fashion with this code:

price.formatMoney(2);

或者如果您想为欧洲指定千位和十进制分隔符.

Or if you want to specify the thousands and decimal separators for Europe.

price.formatMoney(2, ',', '.');

这篇关于将数字四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆