使用toFixed(2)和数学轮来获得正确的舍入 [英] Using toFixed(2) and math round to get correct rounding

查看:172
本文介绍了使用toFixed(2)和数学轮来获得正确的舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个会返回这种格式化值的函数:

I would like to find a function that will return this kind of formatted values :

1.5555 => 1.55
1.5556 => 1.56
1.5554 => 1.55
1.5651 => 1.56

toFixed()和数学回合返回此值:

toFixed() and math round return this value :

1.5651.fixedTo(2) => 1.57

这对于货币四舍五入是有用的。

This will be usefull for money rounding.

推荐答案

这个怎么样?

function wacky_round(number, places) {
    var multiplier = Math.pow(10, places+2); // get two extra digits
    var fixed = Math.floor(number*multiplier); // convert to integer
    fixed += 44; // round down on anything less than x.xxx56
    fixed = Math.floor(fixed/100); // chop off last 2 digits
    return fixed/Math.pow(10, places);
}




1.5554 => 1.55

1.5554 => 1.55

1.5555 => 1.55

1.5555 => 1.55

1.5556 => 1.56

1.5556 => 1.56

1.5651 = > 1.56

1.5651 => 1.56

所以,这有效,但我认为你会发现它不是一种普遍接受的回合方式。
http://en.wikipedia.org/wiki/Rounding#Tie-打破

So, that works, but I think you'll find that it's not a generally-accepted way to round. http://en.wikipedia.org/wiki/Rounding#Tie-breaking

这篇关于使用toFixed(2)和数学轮来获得正确的舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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