我一直在使用Math.Round(myNumber, MidpointRounding.ToEven)
在 C# 中进行服务器端舍入,但是,用户需要“实时”知道服务器端操作的结果是什么,这意味着(避免Ajax请求)创建一个 JavaScript 方法来复制MidpointRounding.ToEven
C# 使用的方法。
MidpointRounding.ToEven 是高斯/银行家四舍五入,描述了一种非常常见的会计系统舍入方法here.
有人对这个有经验么?我在网上找到了例子,但它们并没有四舍五入given小数位数...
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
现场演示:http://jsfiddle.net/NbvBp/
对于看起来更严格的处理(我从未使用过它),你可以尝试这个大数执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)