Skip to content
Numbers and Math
step 1/8

Reading — step 1 of 8

Learn

~2 min readGetting Started

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

js

There's no separate integer-divide operator. Use Math.floor(a / b) for that:

js

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:

js

Don't compare floats with === directly. For "close enough":

js

For money: never use plain numbers. Either work in cents (integers) or use a decimal library.

Special numeric values

js

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:

js

BigInt and Number can't be mixed in arithmetic — convert with BigInt(x) or Number(b).

Parsing strings to numbers

js

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

js

For a random integer in [0, n): Math.floor(Math.random() * n).

Common mistakes

  • Comparing floats with ===. Use Math.abs(a - b) < Number.EPSILON.
  • Using x === NaN. Always returns false. Use Number.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…

Numbers and Math — JavaScript Fundamentals