Beginner · First steps: values, variables and operators · topic 5 of 61 · 25 min
Numbers and Math
Explanation
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.
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)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
| Code | Result | Note |
|---|---|---|
| Number('42') | 42 | Whole text must be a number |
| Number('42px') | NaN | NaN means Not a Number |
| parseInt('42px', 10) | 42 | Reads digits from the start |
| parseFloat('3.75kg') | 3.75 | Reads a decimal from the start |
| Number('') | 0 | Empty 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
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)); // 9Math.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
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.
console.log(9007199254740991 + 2); // 9007199254740992 (wrong!)
console.log(9007199254740991n + 2n); // 9007199254740993n (exact)
// 10n + 1 → TypeError: Cannot mix BigInt and other typesNeed 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
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.
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 personPractice (0/3 done)
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.
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).
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Variables: let, const and varFirst steps: values, variables and operators · same module
- Numbers and mathsPython Programming · First steps in Python
- Numbers and mathsSQL and Databases · Functions, CASE and NULL
- Binary and decimal for networkingComputer Networking (CCNA level) · IPv4 addressing
- Types and variablesC# and .NET · Getting started with C# and .NET
- Variables, basic types and zero valuesGo Programming (backend and cloud) · Getting started with Go
Questions people ask about this
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
What is 00001111 in decimal?Related
Answer: 15
The four bits on the right are on: 8 + 4 + 2 + 1 = 15.
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
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
- This is the last topic of “First steps: values, variables and operators”. The module exam comes next.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.