Skip to content

JavaScript Numbers & Math

JavaScript Numbers

JavaScript has only one type of number. Numbers can be written with, or without decimals.

let x = 3.14;    // A number with decimals
let y = 3;       // A number without decimals

Precision Issues

Integers are accurate up to 15 digits. Floating point arithmetic is not always 100% accurate:

let x = 0.2 + 0.1; // 0.30000000000000004
Fix: To solve this, multiply and divide: let x = (0.2 * 10 + 0.1 * 10) / 10;

NaN - Not a Number

NaN is a reserved word indicating that a number is not a legal number.

let x = 100 / "Apple"; // x is NaN
console.log(isNaN(x));  // true

Number Methods

  • toString(): Returns a number as a string.
  • toFixed(n): Returns a string with the number written with n decimals (e.g., 9.656.toFixed(2) -> "9.66").
  • Number(str): Converts a variable to a number.
  • parseInt(str): Parses a string and returns a whole number.

The Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

Method Description
Math.round(x) Rounds to the nearest integer.
Math.ceil(x) Rounds up to the nearest integer.
Math.floor(x) Rounds down to the nearest integer.
Math.sqrt(x) Returns the square root.
Math.abs(x) Returns the absolute value.
Math.random() Returns a random number between 0 and 1.
Math.ceil(4.4); // 5
Math.floor(4.7); // 4

Random Integer

To get a random integer between 0 and 10: Math.floor(Math.random() * 11);


← Back: Strings | Next: Arithmetic Operators →