Jim*_*mbo 55 javascript rounding
我一直在使用Math.Round(myNumber, MidpointRounding.ToEven)
C#来进行服务器端舍入,但是,用户需要知道"实时"服务器端操作的结果是什么(避免Ajax请求)创建一个JavaScript方法来复制MidpointRounding.ToEven
C#使用的方法.
MidpointRounding.ToEven是高斯/ 银行家舍,所描述的会计系统最常用的舍入方法在这里.
有人对这个有经验么?我在网上找到了例子,但它们没有舍入到给定的小数位数......
Tim*_*own 79
function evenRound(num, decimalPlaces) {
var d = decimalPlaces || 0;
var m = Math.pow(10, d);
var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
var i = Math.floor(n), f = n - i;
var e = 1e-8; // Allow for rounding errors in f
var r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
console.log( evenRound(1.5) ); // 2
console.log( evenRound(2.5) ); // 2
console.log( evenRound(1.535, 2) ); // 1.54
console.log( evenRound(1.525, 2) ); // 1.52
Run Code Online (Sandbox Code Playgroud)
现场演示:http://jsfiddle.net/NbvBp/
对于什么样子的这种更严格的处理(我从来没有用过它),你可以试试这个BigNumber实现.
小智 11
这是不寻常的 stackoverflow,其中底部的答案比公认的要好。刚刚清理了@xims 解决方案并使其更清晰:
function bankersRound(n, d=2) {
var x = n * Math.pow(10, d);
var r = Math.round(x);
var br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r-1) : r;
return br / Math.pow(10, d);
}
Run Code Online (Sandbox Code Playgroud)
接受的答案会绕到给定数量的地方.在此过程中,它调用toFixed将数字转换为字符串.由于价格昂贵,我提供以下解决方案.它将以0.5结尾的数字舍入到最接近的偶数.它不会处理到任意数量的位置的舍入.
function even_p(n){
return (0===(n%2));
};
function bankers_round(x){
var r = Math.round(x);
return (((((x>0)?x:(-x))%1)===0.5)?((even_p(r))?r:(r-1)):r);
};
Run Code Online (Sandbox Code Playgroud)
这是@soegaard提供的很好的解决方案。这是一个小更改,可用于小数点:
bankers_round(n:number, d:number=0) {
var x = n * Math.pow(10, d);
var r = Math.round(x);
var br = (((((x>0)?x:(-x))%1)===0.5)?(((0===(r%2)))?r:(r-1)):r);
return br / Math.pow(10, d);
}
Run Code Online (Sandbox Code Playgroud)
而在此期间-这是一些测试:
console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
console.log(" 2.5 -> 2 : ", bankers_round(2.5) );
console.log(" 1.535 -> 1.54 : ", bankers_round(1.535, 2) );
console.log(" 1.525 -> 1.52 : ", bankers_round(1.525, 2) );
console.log(" 0.5 -> 0 : ", bankers_round(0.5) );
console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
console.log(" 0.4 -> 0 : ", bankers_round(0.4) );
console.log(" 0.6 -> 1 : ", bankers_round(0.6) );
console.log(" 1.4 -> 1 : ", bankers_round(1.4) );
console.log(" 1.6 -> 2 : ", bankers_round(1.6) );
console.log(" 23.5 -> 24 : ", bankers_round(23.5) );
console.log(" 24.5 -> 24 : ", bankers_round(24.5) );
console.log(" -23.5 -> -24 : ", bankers_round(-23.5) );
console.log(" -24.5 -> -24 : ", bankers_round(-24.5) );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8484 次 |
最近记录: |