gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:28:49 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com