jonschlinkert / is-number

JavaScript/Node.js utility. Returns `true` if the value is a number or string number. Useful for checking regex match results, user input, parsed strings, etc.
https://github.com/jonschlinkert
MIT License
258 stars 48 forks source link

Limited to `Number.isSafeInteger` values #17

Open vdh opened 5 years ago

vdh commented 5 years ago

It should probably be mentioned somewhere that this returns false for integer strings that are outside Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER, due to Number.isFinite not being able to handle large integers. e.g.:

const isNumber = require('is-number');
const nines = Array(309).fill('9').join('');
isNumber(nines); // returns false
Number.isFinite(nines); // returns false
yinsang commented 3 years ago

Javascript Infinity is not equal Infinity in Math. While nines‘s Number value is 'bigger' than Number.MAX_VALUE , JS understand it as an Infinity number. I think it is expected that returns false as isNumber(Infinity) return false. JS can't handle the number outside of JS.

yinsang commented 3 years ago

you may need another function like

function isBigNumber(str) {
    return Number(str) === Infinity && str.split('').every(item => (Number(item)) < 10)
}
vdh commented 3 years ago

@yinsang The stated goal of this library, from the readme:

Why is this needed?

In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:

This library was designed to bypass unintuitive limits/deficiencies with the native JS handling of numbers. Large numbers returning false is another one of those limits, and if it's not going to be handled, it should be documented as something that is not supported for the library. It shouldn't remain an undocumented mystery that people have to trip over to find out.

Furthermore, Infinity is never a number, it's a concept. You can't just hand-wave it as "JS understand it as an Infinity number", that's not a good excuse. "Infinity number" isn't a thing. Either something is a number, or it's Infinity. Large numbers don't stop being numbers and don't magically become Infinity just because of a defect in the programming language. BigInt was added precisely because it's important to be able to support handling bigger numbers because numbers don't just magically stop being numbers because of hardware limits.

yinsang commented 3 years ago

without guess, we need author's response. @jonschlinkert