Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rounding negative number with fractional portion being exactly 0.5 #29

Open
yvele opened this issue Aug 9, 2023 · 1 comment
Open

Comments

@yvele
Copy link
Contributor

yvele commented Aug 9, 2023

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

@sindresorhus
Copy link
Owner

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}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants