Number
Whenever you are handling numbers in any programming language you need to be aware of the idiosyncrasies of how the language handles numbers. Here are a few critical pieces of information about numbers in JavaScript that you should be aware of.
Core Type
JavaScript has only one number type. It is a double-precision 64-bit Number
. Below we discuss its limitations along with a recommended solution.
Decimal
For those familiar with doubles / float in other languages, you would know that binary floating point numbers do not map correctly to Decimal numbers. A trivial (and famous) example with JavaScript's built in numbers is shown below:
For true decimal math use
big.js
mentioned below.
Integer
The integer limits represented by the built in number type are Number.MAX_SAFE_INTEGER
and Number.MIN_SAFE_INTEGER
.
Safe in this context refers to the fact that the value cannot be the result of a rounding error.
The unsafe values are +1 / -1
away from these safe values and any amount of addition / subtraction will round the result.
To check safety you can use ES6 Number.isSafeInteger
:
JavaScript will eventually get BigInt support. For now, if you want arbitrary precision integer math use
big.js
mentioned below.
big.js
Whenever you use math for financial calculations (e.g. GST calculation, money with cents, addition etc) use a library like big.js which is designed for
Perfect decimal math
Safe out of bound integer values
Installation is simple:
Quick Usage example:
Do not use this library for math used for UI / performance intensive purposes e.g charts, canvas drawing etc.
NaN
When some number calculation is not representable by a valid number, JavaScript returns a special NaN
value. A classic example is imaginary numbers:
Note: Equality checks don't work on NaN
values. Use Number.isNaN
instead:
Infinity
The outer bounds of values representable in Number are available as static Number.MAX_VALUE
and -Number.MAX_VALUE
values.
Values outside the range where precision isn't changed are clamped to these limits e.g.
Values outside the range where precision is changed resolve to special values Infinity
/-Infinity
e.g.
Of-course, these special infinity values also show up with arithmetic that requires it e.g.
You can use these Infinity
values manually or using static members of the Number
class as shown below:
Fortunately comparison operators (<
/ >
) work reliably on infinity values:
Infinitesimal
The smallest non-zero value representable in Number is available as static Number.MIN_VALUE
Values smaller than MIN_VALUE
("underflow values") are converted to 0.
Further intuition: Just like values bigger than
Number.MAX_VALUE
get clamped to INFINITY, values smaller thanNumber.MIN_VALUE
get clamped to0
.
Last updated