typestar

Numbers in JavaScript

One float type, so integer checks and precision need care.

console.log(0.1 + 0.2, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log(Number.isInteger(5.0), Number.isInteger(5.5));
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 === 2 ** 53 + 1);

console.log((1234.5678).toFixed(2), (0.000001234).toExponential(2));
console.log(parseInt("08", 10), Number("08"), Number(""), Number("x"));
console.log(Math.trunc(-4.7), Math.round(-4.5), Math.floor(-4.5));
console.log((255).toString(16), parseInt("ff", 16));
console.log(10n ** 20n, typeof 10n);

How it works

  1. Number.isInteger and isFinite beat the global versions.
  2. 0.1 + 0.2 is not 0.3: compare with a tolerance.
  3. toFixed returns a string, and rounds half away from zero.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
488
Tokens
174
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 130 seconds.

Type this snippet

Step 5 of 5 in Bindings & values, step 5 of 43 in Language basics.

← Previous Next →