roundTo
must be consistent with Math.round
when dealing with fractional portion being exactly 0.5:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#description
If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +β.
This differs from many languages'
round()
functions, which often round half-increments away from zero, giving a different result in the case of negative numbers with a fractional part of exactly 0.5.
// With negative numbers
Math.round(-1.5); // -1
Math.round(-1.51); // -2
// With positive numbers
Math.round(1.5); // 2
I suggest that this should be the behavior a JavaScript developer should expect:
t.is(roundTo(0.5, 0), 1);
- t.is(roundTo(-0.5, 0), -1);
+ t.is(roundTo(-0.5, 0), 0); // Note that we intentionally DON'T have -0 here
t.is(roundTo(1.005, 2), 1.01);
- t.is(roundTo(-1.005, 2), -1.01);
+ t.is(roundTo(-1.005, 2), -1);
Previous discussions:
Note also that's how Lodash works:
See also https://en.wikipedia.org/wiki/Rounding#Comparison_of_approaches_for_rounding_to_an_integer
I think the exact description is "Half Up (toward +β)".
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too