There is a discrepancy between how C# or Python rounds a decimal number and how Javascript handles it. I've already found this answer banker-rounding, but this solution does not work in my case and causes different results between server and client.
Suppose I have a variable number
that its value is from 1.36500000000001
to 1.36500000000009
.
In C#:
// 1.36500000000001m
Math.Round(decimal_number, 2, MidpointRounding.ToEven)
// 1.37
In Python:
Decimal(str(number)).quantize(Decimal('0.01')), ROUND_HALF_EVEN))
# 1.37
But in Javascript: based on different functions of banker-rounding
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);
}
bankersRound(number, 2)
// 1.36
Has the community found a solution for Javascript? Is there any other implementation in Javascript?
source https://stackoverflow.com/questions/77595614/equivalnet-of-c-sharp-or-python-even-rounding-in-javascript
Comments
Post a Comment