问题描述
我一直在C#中使用 Math.Round(myNumber,MidpointRounding.ToEven)
进行服务器端舍入,但是,用户需要知道'live'服务器端操作的结果是什么意思(避免)请求)创建一个JavaScript方法来复制C#使用的 MidpointRounding.ToEven
方法。
I have been using Math.Round(myNumber, MidpointRounding.ToEven)
in C# to do my server-side rounding, however, the user needs to know 'live' what the result of the server-side operation will be which means (avoiding an Ajax request) creating a JavaScript method to replicate the MidpointRounding.ToEven
method used by C#.
MidpointRounding.ToEven是Gaussian / ,一种非常常见的会计系统舍入方法。
MidpointRounding.ToEven is Gaussian/banker's rounding, a very common rounding method for accounting systems described here.
有没有人有这方面的经验?我在网上找到了例子,但它们没有舍入到给定的小数位数...
Does anyone have any experience with this? I have found examples online, but they do not round to a given number of decimal places...
推荐答案
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
现场演示:
对于看起来更严格的处理方式(我是从未使用过它,您可以尝试实施。
For what looks like a more rigorous treatment of this (I've never used it), you could try this BigNumber implementation.
这篇关于高斯/银行家在JavaScript中的四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!