Reading — step 1 of 8
Learn
JavaScript has only one number type: a 64-bit IEEE 754 floating-point. No separate int and float types like most languages. That keeps the language simple, but it has consequences you should know.
The arithmetic operators
There's no separate integer-divide operator. Use Math.floor(a / b) for that:
Math.floor rounds toward negative infinity. Math.trunc chops the decimal. They differ for negatives.
The float-precision surprise
Because all numbers are IEEE 754 floats, you'll hit a famous quirk:
Don't compare floats with === directly. For "close enough":
For money: never use plain numbers. Either work in cents (integers) or use a decimal library.
Special numeric values
NaN propagates: any arithmetic involving NaN produces NaN. To detect it, use Number.isNaN(x), NOT x === NaN.
BigInt — for arbitrary-precision integers
For integers larger than Number.MAX_SAFE_INTEGER (2⁵³−1), use BigInt:
BigInt and Number can't be mixed in arithmetic — convert with BigInt(x) or Number(b).
Parsing strings to numbers
Always pass the radix to parseInt (parseInt(s, 10) for decimal). Without it, strings starting with 0 were historically interpreted as octal.
Useful Math methods
For a random integer in [0, n): Math.floor(Math.random() * n).
Common mistakes
- Comparing floats with
===. UseMath.abs(a - b) < Number.EPSILON. - Using
x === NaN. Always returns false. UseNumber.isNaN(x). - Forgetting the radix in
parseInt. - Using plain numbers for money. Work in cents or use Decimal.js.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…