JavaScript Tutorial menu

JavaScript Numbers

JavaScript has a single number type for whole numbers and decimals, plus a Math object full of helpful tools.

Writing Numbers

Example

javascript
let rollNo = 42;          // whole number
let weight = 64.5;        // decimal
let population = 20e6;    // 20000000 (20 million)
let salary = 85_000;      // underscores only make it easier to read

Decimal Accuracy

Computers store decimals in binary, so some results are slightly off:

Example

javascript
console.log(0.1 + 0.2);
Output
0.30000000000000004

For money and display, round the result with toFixed(). It returns a string with the given number of decimals.

Example

javascript
let price = 199.456;
console.log(price.toFixed(2));   // "199.46"
console.log((0.1 + 0.2).toFixed(2)); // "0.30"

Text to Number

Values from forms are strings. Convert them before doing maths:

FunctionExampleResult
Number()Number("45.5")45.5
parseInt()parseInt("45.9 kg")45
parseFloat()parseFloat("45.9 kg")45.9
Number()Number("abc")NaN

Example

html
<!DOCTYPE html>
<html>
<body>

<p>Price: <input id="price" value="1200"></p>
<p>Quantity: <input id="qty" value="3"></p>
<button onclick="calc()">Calculate</button>
<p id="demo"></p>

<script>
function calc() {
  const price = Number(document.getElementById("price").value);
  const qty = Number(document.getElementById("qty").value);
  const total = price * qty;
  document.getElementById("demo").innerHTML = "Total: Rs " + total.toLocaleString();
}
</script>

</body>
</html>
Try it Yourself »
Output
Total: Rs 3,600

toLocaleString() adds commas to big numbers, which makes prices easier to read.

NaN and Infinity

  • NaN means "Not a Number". You get it when maths is done on text that is not a number, like "abc" * 2
  • Number.isNaN(value) checks for it
  • Dividing by zero gives Infinity

Example

javascript
console.log("ten" * 2);            // NaN
console.log(Number.isNaN("ten" * 2)); // true
console.log(10 / 0);               // Infinity

The Math Object

MethodExampleResult
Math.round(x)Math.round(4.6)5
Math.floor(x)Math.floor(4.9)4
Math.ceil(x)Math.ceil(4.1)5
Math.max(...)Math.max(3, 9, 2)9
Math.min(...)Math.min(3, 9, 2)2
Math.abs(x)Math.abs(-7)7
Math.sqrt(x)Math.sqrt(49)7
Math.PIMath.PI3.14159...

Random Numbers

Math.random() gives a random decimal from 0 up to (but not including) 1. To get a whole number from 1 to 6, like a dice:

Example

html
<!DOCTYPE html>
<html>
<body>

<h2>Ludo Dice</h2>
<button onclick="roll()">Roll</button>
<p id="dice" style="font-size:40px">?</p>

<script>
function roll() {
  const value = Math.floor(Math.random() * 6) + 1;
  document.getElementById("dice").innerHTML = value;
}
</script>

</body>
</html>
Try it Yourself »

Math.random() * 6 gives 0 to 5.99, Math.floor turns it into 0 to 5, and + 1 makes it 1 to 6.

toFixed() returns a string. If you need to keep calculating, convert back with Number(x.toFixed(2)).

Exercise

Exercise

What is the result of Math.ceil(7.2)?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp