作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想找到一个函数来返回这种格式化的值:
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/
我是一名优秀的程序员,十分优秀!