After this lesson you can calculate with numbers, avoid the classic decimal surprise, turn text into numbers, round values for display, and use the built-in Math object.
One kind of number
Unlike many languages, JavaScript has a single number type for 5 and 5.25 alike. You write them directly in your code.
console.log(1_000_000); // 1000000, underscores are only for readability
console.log(Number.isInteger(5.0)); // trueArithmetic uses the operators you know: +, -, *, /, plus % (remainder) and ** (power). The Operators lesson covers them in detail. Here we focus on how numbers behave.
The 0.1 + 0.2 surprise
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // falseThis is not a JavaScript bug. Computers store numbers in binary, and some decimal fractions, like one tenth, have no exact binary form, just as one third has no exact decimal form. Almost every language shows the same result.
What to do about it:
- For display, round:
(0.1 + 0.2).toFixed(2)gives"0.30". - For comparison, check that the difference is tiny:
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILONistrue. - For money, work in the smallest unit, such as whole cents or paise, as integers, and convert to a decimal only when showing the value.
Note that toFixed returns a string, not a number.
NaN and Infinity
Some calculations have no sensible numeric answer.
console.log(0 / 0); // NaN
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Number("abc")); // NaNNaN stands for "not a number". It is, confusingly, of type number. It spreads: any calculation that includes NaN gives NaN. And it is the only value not equal to itself.
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("abc")); // false
console.log(isNaN("abc")); // true (the old global converts first)Prefer Number.isNaN. The older global isNaN first converts its argument to a number, so it calls the text "abc" "not a number" in a way that can mislead.
Turning text into numbers
Data from forms and the page arrives as text. Convert it before doing sums.
console.log(Number("42")); // 42
console.log(Number("")); // 0
console.log(Number("42px")); // NaN
console.log(parseInt("42px")); // 42
console.log(parseFloat("3.5kg")); // 3.5
console.log(parseInt("px42")); // NaNNumber(text)is strict: the whole text must be a valid number, or you getNaN. An empty string gives0, which surprises people.parseInt(text)andparseFloat(text)read as much as they can from the start and ignore the rest.
When you want a whole number from user input, Number(text) plus a check for NaN is usually the safer route, because it does not silently accept "42px".
Rounding
There are four common ways to turn a decimal into a whole number, and they differ most for negatives.
console.log(Math.round(2.5), Math.round(-2.5), Math.round(2.4)); // 3 -2 2
console.log(Math.floor(-2.5), Math.ceil(2.1), Math.trunc(-2.9)); // -3 3 -2| Method | Meaning |
|---|---|
Math.round(x) |
Nearest whole number. A .5 goes towards positive infinity |
Math.floor(x) |
Down, towards negative infinity |
Math.ceil(x) |
Up, towards positive infinity |
Math.trunc(x) |
Cut off the decimals, towards zero |
To round to decimal places, use toFixed(2) for display, or Math.round(x * 100) / 100 to keep a number.
The Math object
Math is a built-in object with useful values and functions. You never create it; you just use it.
console.log(Math.max(3, 9, 2)); // 9
console.log(Math.min(3, 9, 2)); // 2
console.log(Math.max(...[4, 8, 1])); // 8 (spread a list into arguments)
console.log(Math.sqrt(81)); // 9
console.log(2 ** 10, Math.pow(2, 10)); // 1024 1024
console.log(Math.PI); // 3.141592653589793
console.log(Math.abs(-7)); // 7Math.max() with no arguments returns -Infinity, and Math.min() returns Infinity. Those are the natural "starting values" for those functions.
Random numbers
Math.random() returns a decimal from 0 up to, but never including, 1. Scale and floor it to get a range.
<button id="roll">Roll a die</button>
<p id="result">Press the button.</p>
<script>
function rollDie() {
return Math.floor(Math.random() * 6) + 1; // 1 to 6
}
document.getElementById("roll").addEventListener("click", function () {
document.getElementById("result").textContent = "You rolled " + rollDie();
});
</script>The recipe for whole numbers from min to max, both included, is Math.floor(Math.random() * (max - min + 1)) + min. Math.random is fine for games and shuffling, but it is not secure, so never use it for passwords or tokens.
Formatting for people
toLocaleString formats a number using local conventions, such as thousands separators.
console.log((1234567.891).toLocaleString("en-US")); // 1,234,567.891
console.log((1234567.891).toLocaleString("en-IN")); // 12,34,567.891Results depend on the locale data available in the environment, so check them on your target browsers. Number conversion to other bases also exists, for example (255).toString(16) gives "ff".
Common mistakes
- Comparing decimals with
===. Round them first or compare with a tolerance. - Adding numbers that are really strings.
"5" + 3is"53". Convert withNumber()first. - Using
x === NaN. It is alwaysfalse. UseNumber.isNaN(x). - Forgetting
toFixedreturns text. Convert back withNumber(...)if you need to calculate more. - Off-by-one in dice rolls. Without the
+ 1, your die shows 0 to 5. - Doing money in decimals. Store whole cents as integers.
Exercise
- Calculate a total of
19.99 * 3and print it raw, then withtoFixed(2). - Write a snippet that picks a random whole number between 10 and 20, inclusive. Run it several times.
- Convert the text
"250"to a number, add 50, and print the result. - Check what
Math.round(-0.5)andMath.floor(-0.5)give, and explain the difference in a comment.
Next: Strings. For a ready-made calculator to test your results against, try the percentage calculator.
Key points
- JavaScript has one number type for whole numbers and decimals, stored as floating point.
- Decimal fractions are not always exact, so 0.1 + 0.2 gives 0.30000000000000004. Round for display with toFixed.
- NaN means "not a number", is not equal to itself, and is detected with Number.isNaN.
- Math.round, floor, ceil and trunc round in different ways, especially for negative numbers.
- Math.random gives a number from 0 up to but not including 1, which you scale to get dice rolls and similar values.