Deeper into Math

In JS, all numbers are stored in the 64-bit IEEE 754 format (floating-point numbers). This gives a huge range, but has its quirks with precision.

1. Rounding (Math)

  • Math.floor: Rounds down (3.13, -1.1-2).
  • Math.ceil: Rounds up (3.14).
  • Math.round: Rounds to the nearest integer (3.54).
  • Math.trunc: Simply cuts off the fractional part (removes everything after the dot).

2. Pretty Output (toFixed)

The toFixed(n) method rounds a number to n decimal places and turns it into a STRING.

let num = 12.3456;
alert( num.toFixed(2) ); // "12.35" (rounded according to math rules)
Warning

Precision Trap: You've probably heard that 0.1 + 0.2 === 0.3 returns false. This isn't a JS bug, it's a feature of storing numbers in binary format. We'll discuss this in detail at the end of the module.

Tip

If you need to round a number to a certain decimal place (e.g., hundredths), but keep it as a NUMBER, use: +num.toFixed(2). The unary plus returns the Number type.