Skip to content
techsnow

JavaScript Basics

Numbers and Math

console.log(10 / 3);              // 3.3333333333333335
console.log((10 / 3).toFixed(2)); // "3.33"
console.log(Math.round(4.6));     // 5
console.log(Math.floor(4.9));     // 4
console.log(Math.ceil(4.1));      // 5
console.log(Math.max(3, 9, 2));   // 9
console.log(Math.random());       // a random number from 0 to 1

A random whole number

// a dice roll: 1 to 6
const dice = Math.floor(Math.random() * 6) + 1;

Formatting numbers

const price = 1999.5;
console.log(price.toLocaleString("en-PK")); // "1,999.5"