javascript - 使用 toFixed(2) 和数学舍入获得正确的舍入

标签 javascript rounding

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

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

toFixed() 和数学回合返回这个值:

1.5651.fixedTo(2) => 1.57

这对四舍五入很有用。

最佳答案

这个怎么样?

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.5555 => 1.55

1.5556 => 1.56

1.5651 => 1.56

所以,这行得通,但我认为您会发现这不是一种普遍接受的舍入方式。 http://en.wikipedia.org/wiki/Rounding#Tie-breaking

关于javascript - 使用 toFixed(2) 和数学舍入获得正确的舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861055/

相关文章:

c# - 设置精度c#

javascript - Flask API 向简单的 HTML+JS+CSS Web 应用程序提供 JSON 文件,同时保持其安全

javascript - 在 d3 力导向图中使用曲线

javascript - Scriptaculous 自动完成 : Returns a List of Links, 希望单击链接而不是自动填充输入字段

javascript - 如何在 2D Canvas 中实现缩放功能?

javascript - 从 JS 中的构造函数返回 this

c++ - 如何重现 C++ 双舍入问题

firefox - FireFox 3.6.15+ 中图像的圆 Angular 仍然不起作用?

c++ - 在 C++ 中将数字显式舍入到小数点后 7 位以上

c# - 除法不返回 double