adr*_*334 3 javascript rounding
我想找到一个函数,它将返回这种格式化的值:
1.5555 => 1.55
1.5556 => 1.56
1.5554 => 1.55
1.5651 => 1.56
Run Code Online (Sandbox Code Playgroud)
toFixed()和math round返回此值:
1.5651.fixedTo(2) => 1.57
Run Code Online (Sandbox Code Playgroud)
这将有助于金钱四舍五入.
这个怎么样?
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);
}
Run Code Online (Sandbox Code Playgroud)
1.5554 => 1.55
1.5555 => 1.55
1.5556 => 1.56
1.5651 => 1.56
所以,这有效,但我认为你会发现这不是一种普遍接受的回合方式. http://en.wikipedia.org/wiki/Rounding#Tie-breaking