-
-
Notifications
You must be signed in to change notification settings - Fork 11
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
Returns NaN
instead of correct result for large or small numbers
#7
Comments
@sindresorhus The solution to this is probably to get rid of the concise syntax that currently makes this all work. The way the rounding works right now, when you plug in Number(Math.round(1e16 + 'e4') + 'e-4'); It works because 1e16 is instantly converted to So while coercing the string If you want to keep the code terse then maybe just add a disclaimer in the documentation. If you want it to be robust enough to handle very large and very small numbers (or extreme precisions), multiplication and division instead of relying on coercing strings to numbers multiple times would be better. |
I think it should be able to handle large numbers. |
@sindresorhus Looking into this some more, it looks like there are limited options. 1. Use the naive rounding formula that I think most people use: function round(n, precision) {
var power = Math.pow(10, precision);
return Math.round(n * power) / power;
} This works for really large numbers and doesn't require converting back and forth between strings and numbers. But it fails when floating point arithmetic fails. For instance: 2. Use Number.toLocaleString This is a rough implementation, but it works. If the precision is negative, then we need to figure out how many significant digits to use. I did this by getting the length of the integer portion of the number as a string and adding it to the given precision, but there might be a nicer way. If the precision is positive, then we can use the built-in function round(n, precision) {
if (precision < 0) {
const length = String(n).split('.')[0].length;
return parseFloat(n.toLocaleString('en', { maximumSignificantDigits: length + precision, useGrouping: false }));
}
return parseFloat(n.toLocaleString('en', { maximumFractionDigits: precision, useGrouping: false }));
} This only handles the 3. Current implementation Unless there is another alternative, maybe just include a note in the readme that says that numbers above X are not supported. |
Could we maybe do |
@sindresorhus This is causing the NaN bug in atomiclabs/hyperdex#119 |
Large positive numbers:
Negative numbers of large magnitude:
Numbers of small magnitude:
The text was updated successfully, but these errors were encountered: