sindresorhus/round-to

Do you want to work on this issue?

You can request for a bounty in order to promote it!

Rounding negative number with fractional portion being exactly 0.5 #29

yvele posted onGitHub

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 +∞)".

Screenshot 2023-08-09 at 09 26 18


I would prefer to keep the existing logic. It matches the behavior of many other (and better) programming languages.

However, we could add an option to opt into the suggested behavior. The option could maybe be called {roundTowardZero: true}.

posted by sindresorhus over 1 year ago

Fund this Issue

$0.00
Funded
Only logged in users can fund an issue

Pull requests