Skip to content

Beginner · First steps: values, variables and operators · topic 5 of 61 · 25 min

Numbers and Math

Explanation

JavaScript has one number type for whole numbers and decimals, stored in a binary format, so 0.1 + 0.2 is not exactly 0.3. For money, calculate in paise (whole numbers) and format only for display. Math gives rounding and other helpers, and BigInt handles huge whole numbers.

One number type

Many languages have separate types for whole numbers and decimals. JavaScript has just one, number, which is a 64-bit floating-point value (the IEEE 754 standard). Floating point means the decimal point can "float": the computer stores a number as digits plus a position, in binary.

Why 0.1 + 0.2 is not 0.3

Some decimals, like 0.1, cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimal (0.3333…). So tiny errors appear.

javascript
console.log(0.1 + 0.2);          // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);  // false
console.log((0.1 + 0.2).toFixed(2)); // '0.30' (a string, for display)
Careful: Never use floating-point maths for money and then compare exact values. Store amounts in the smallest unit (paise, cents) as whole numbers: ₹199.99 becomes 19999 paise. Add and multiply whole numbers, and divide by 100 only when you show the price.
javascript
const pricesInPaise = [19999, 4950, 100];
const totalPaise = pricesInPaise.reduce((sum, p) => sum + p, 0);
console.log(totalPaise);              // 25049
console.log((totalPaise / 100).toFixed(2)); // '250.49'

Turning text into numbers

CodeResultNote
Number('42')42Whole text must be a number
Number('42px')NaNNaN means Not a Number
parseInt('42px', 10)42Reads digits from the start
parseFloat('3.75kg')3.75Reads a decimal from the start
Number('')0Empty text becomes 0: be careful

NaN is a special number value meaning "this is not a valid number". Any maths with NaN gives NaN, and NaN is not equal even to itself. Test it with Number.isNaN(value). Infinity appears when you divide a non-zero number by 0.

Rounding and Math

javascript
console.log(Math.round(2.5));   // 3
console.log(Math.round(-2.5));  // -2 (rounds toward +infinity at .5)
console.log(Math.floor(2.9));   // 2 (down)
console.log(Math.ceil(2.1));    // 3 (up)
console.log(Math.trunc(-2.9));  // -2 (cuts off the decimals)
console.log(Math.max(4, 9, 1)); // 9
console.log(Math.min(4, 9, 1)); // 1
console.log(Math.abs(-7));      // 7
console.log(Math.sqrt(81));     // 9

Math.random() gives a decimal from 0 (included) up to 1 (not included). To get a whole number from 1 to 6, like a dice: Math.floor(Math.random() * 6) + 1. Do not use Math.random for passwords or OTPs; it is not secure. Use crypto.getRandomValues instead.

Formatting for people: Indian grouping

javascript
const amount = 1234567.5;
console.log(amount.toFixed(2));  // '1234567.50'
console.log(new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(amount));
// '₹12,34,567.50' (lakh and crore grouping)

Very big whole numbers: BigInt

A number can hold whole numbers exactly only up to Number.MAX_SAFE_INTEGER, which is 9007199254740991 (about 9 quadrillion). Beyond that, adding 1 may give a wrong answer. BigInt stores any whole number exactly; write it with an n at the end. You cannot mix BigInt and number in one sum without converting.

javascript
console.log(9007199254740991 + 2);  // 9007199254740992 (wrong!)
console.log(9007199254740991n + 2n); // 9007199254740993n (exact)
// 10n + 1  → TypeError: Cannot mix BigInt and other types
Tip: IDs from databases (like a 19-digit Twitter/X id) can be bigger than MAX_SAFE_INTEGER. Keep them as strings in JavaScript, not numbers.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Numbers and Math · 1/7

Numbers and Math

In this lesson you will see how JavaScript stores numbers and how to handle money safely.

Prefer a video by a teacher? Find free videos on “javascript numbers floating point 0.1 + 0.2 math bigint” on YouTube ↗

In real life: A restaurant bill split on UPI

A food app splits ₹1,000 between three friends. 1000 / 3 is 333.333…, which cannot be paid. The app works in paise: 100000 paise divided by 3 is 33333 each, with 1 paisa left over, which it adds to the first person. Everyone pays an exact amount, and the totals match the bill.

javascript
const billPaise = 100000;
const people = 3;
const share = Math.floor(billPaise / people);
const leftover = billPaise - share * people;
console.log(share, leftover);                 // 33333 1
console.log(((share + leftover) / 100).toFixed(2)); // '333.34' for the first person

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function rollDice(randomValue) that turns a number from Math.random() (0 up to but not including 1) into a dice roll from 1 to 6. The random value is passed in so it can be tested.

Task 2 · Code · Javascript

Write a function totalInRupees(prices) that takes an array of prices in rupees with paise (like 199.99) and returns the total as a string with exactly two decimals. Avoid floating-point errors by adding in paise: convert each price with Math.round(price * 100).

Task 3 · Code · Javascript

Write a function parseQuantity(text) that reads a quantity typed by a user. Return the whole number if the text is a valid number like "3" or " 12 ", and return null for anything else ("", "abc", "2.5" is allowed and should return 2.5).

Quick quiz

Question 1

1.What does 0.1 + 0.2 === 0.3 give?

Question 2

2.What is the safest way to store ₹199.99 for calculations?

Question 3

3.What is parseInt('42px', 10)?

Question 4

4.What is NaN === NaN?

Question 5

5.What does Math.floor(-2.5) give?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does 0.1 + 0.2 === 0.3 give?

Answer: false

0.1 + 0.2 is 0.30000000000000004 in binary floating point.

What is the safest way to store ₹199.99 for calculations?

Answer: 19999 paise as a whole number

Whole numbers are exact, so store the smallest unit.

What is parseInt('42px', 10)?

Answer: 42

parseInt reads digits from the start and stops at the first non-digit.

What is NaN === NaN?

Answer: false

NaN is not equal to anything, even itself. Use Number.isNaN.

What does Math.floor(-2.5) give?

Answer: -3

floor always rounds down, toward minus infinity, so -2.5 becomes -3.

Which expression gives the price after a 15% discount?Related

Answer: price * 0.85

Paying 85% of the price is the same as taking 15% off.

From Numbers and maths

What is 00001111 in decimal?Related

Answer: 15

The four bits on the right are on: 8 + 4 + 2 + 1 = 15.

From Binary and decimal for networking

Which of these is NOT a primitive type?Related

Answer: array

Arrays are objects. The primitives are string, number, bigint, boolean, undefined, null and symbol.

From Values and types

Which type holds true or false?Related

Answer: bool

bool has exactly two values: true and false.

From Types and variables

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “First steps: values, variables and operators”. The module exam comes next.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.

← Previous: Operators and type coercion