JavaScript Numbers and Math

JavaScript has one number type for whole numbers and decimals.

let whole = 42;
let decimal = 3.14;
let big = 1e6;      // 1000000
console.log(whole + decimal);
console.log(big);
Output of the above program is

45.14
1000000


Special values

console.log(10 / 0);
console.log(Number("abc"));
console.log(isNaN("abc"));
Output of the above program is

Infinity
NaN
true


Decimal numbers and rounding

Computers store decimals in binary, so some sums are not exact.

console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
console.log((3.14159).toFixed(2));
Output of the above program is

0.30000000000000004
0.30
3.14

toFixed() returns a string. Use Number() on it if you need a number again. For money, calculate in the smallest unit (paise, cents) as whole numbers.


The Math object

MethodResult
Math.round(4.6)5
Math.floor(4.9)4 (round down)
Math.ceil(4.1)5 (round up)
Math.max(3, 9, 5)9
Math.min(3, 9, 5)3
Math.sqrt(16)4
Math.pow(2, 3)8
Math.abs(-7)7
Math.PI3.14159…
console.log(Math.round(4.6));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.max(3, 9, 5));
console.log(Math.sqrt(16));
Output of the above program is

5
4
5
9
4


Random numbers

Math.random() gives a decimal from 0 up to (but not including) 1. Multiply and round to get whole numbers.

// random whole number from 0 to 9
let n = Math.floor(Math.random() * 10);

// random whole number from 1 to 6, like a dice
let dice = Math.floor(Math.random() * 6) + 1;

The result is different every time you run it.

Note: Do not use Math.random() for passwords or security. Use crypto.getRandomValues() instead.

Summary

  • All numbers are one type.
  • Watch out for NaN, Infinity and 0.1 + 0.2.
  • Use Math methods for rounding, power, root and random numbers.
  • Next: Conditional Statements.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.