IsNumber
Well tested 'is number' checks, that can accept number-like strings, and non-finite values as desired.
There are a lot of is number
tests out there. Many of them don't work quite right. Others use a different
definition of is number
than you might want. So after spending way too much time for such a simple thing,
here are four checks:
Function | number literals | number-like strings | Infinity and NaN | Infinity and NaN strings | other strings |
---|
isNumeric | true | true | true | true | false |
isNumber | true | false | true | false | false |
isFiniteNumeric | true | true | false | false | false |
isFiniteNumber | true | false | false | false | false |
Table of Contents
Installation
npm install --save @toolbuilder/isnumber
Getting Started
This is a dual package,
so named exports are available for both CommonJS and ES modules.
import { isNumeric, isFiniteNumeric, isNumber, isFiniteNumber } from '@toolbuilder/isnumber'
console.log(isNumeric('1.234'))
console.log(isFiniteNumeric(42.54))
console.log(isNumber('1.234'))
console.log(isFiniteNumber(-Infinity))
API
API documentation follows.
isNumber
Test if n is a number.
Includes Infinities and NaN, does not include strings that look like numbers
Parameters:
isNumber(1.23)
isNumber(Infinity)
isNumber(NaN)
isNumber('1.23')
Returns boolean true if is number, false otherwise
isNumeric
Test if n is a number, or string that parses to a number. Includes infinities and NaN.
Non-finite strings are: 'Infinity', '-Infinity', and 'NaN'.
Parameters:
isNumeric(1.23)
isNumeric('Infinity')
isNumeric(NaN)
isNumeric('1.23')
isNumeric('hi')
Returns boolean true if is numeric, false otherwise
isFiniteNumber
Test if n is a finite number.
Does not include infinities, NaN, or strings that look like numbers.
Parameters:
isFiniteNumber(1.23)
isFiniteNumber(Infinity)
isFiniteNumber(NaN)
isFiniteNumber('1.23')
Returns boolean true if is a finite number, false otherwise
isFiniteNumeric
Test if n is a finite number, or string that parses to a finite number.
Does not include infinities, NaN
Parameters:
isFiniteNumeric(1.23)
isFiniteNumeric('Infinity')
isFiniteNumeric(NaN)
isFiniteNumeric('1.23')
isFiniteNumeric('hi')
Returns boolean true if is a finite number, false otherwise
Credits
The isFiniteNumeric
implementation, and the most of the tests were copied from this
site. I found these tests on Stack Overflow
in an answer by 'CMS'. Thanks!
Contributing
Contributions are welcome. Please create a pull request.
- I use pnpm instead of npm.
- Run the unit tests with
pnpm test
- Package verification requires pnpm to be installed globally.
npm install -g pnpm
pnpm install
pnpm build
to build cjs, docs, and *.d.tspnpm run check:packfile
to test against ES and CommonJS projects, as well as Electronpnpm run check
to validate the package is ready for commit
Issues
This project uses Github issues.
License
MIT