9. JavaScript Numbers and Math
What you will learn
- How JavaScript handles numbers
- Converting text to numbers and formatting results
- Rounding with the
Mathobject - Random numbers
Numbers
JavaScript has a single number type for whole and decimal values. Special values include Infinity (for example 1 / 0) and NaN (not a number).
Converting text to numbers
| Function | Behaviour |
|---|---|
Number("42") |
Converts the whole string, or gives NaN |
parseInt("42px") |
Reads a whole number from the start and ignores the rest |
parseFloat("3.5kg") |
Reads a decimal number from the start |
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Number('42') = " + Number("42") + "<br>" +
"Number('42px') = " + Number("42px") + "<br>" +
"parseInt('42px') = " + parseInt("42px", 10) + "<br>" +
"parseFloat('3.5kg') = " + parseFloat("3.5kg");
</script>
Output (after the script runs)
Number(’42’) = 42
Number(’42px’) = NaN
parseInt(’42px’) = 42
parseFloat(‘3.5kg’) = 3.5
Always pass 10 as the second value of parseInt to say you want a normal decimal number.
Formatting numbers
Example
<p id="demo"></p>
<script>
const price = 1234.5678;
document.getElementById("demo").innerHTML =
"toFixed(2): " + price.toFixed(2) + "<br>" +
"toLocaleString: " + price.toLocaleString("en-US") + "<br>" +
"As money: " + price.toLocaleString("en-US", { style: "currency", currency: "USD" });
</script>
Output (after the script runs)
toFixed(2): 1234.57
toLocaleString: 1,234.568
As money: $1,234.57
toFixed() returns a string, so convert it back with Number() if you need to calculate with it.
The Math object
| Method | What it does |
|---|---|
Math.round(x) |
Nearest whole number |
Math.ceil(x) |
Round up |
Math.floor(x) |
Round down |
Math.trunc(x) |
Remove the decimal part |
Math.abs(x) |
Remove the minus sign |
Math.max(a, b, ...), Math.min(...) |
Largest and smallest |
Math.pow(x, y), Math.sqrt(x) |
Power and square root |
Math.PI |
The value of pi |
Math.random() |
Random decimal from 0 up to (not including) 1 |
Example
<p id="demo"></p>
<script>
const n = 4.6;
document.getElementById("demo").innerHTML =
"round: " + Math.round(n) + "<br>" +
"ceil: " + Math.ceil(n) + "<br>" +
"floor: " + Math.floor(n) + "<br>" +
"max of 3, 9, 5: " + Math.max(3, 9, 5) + "<br>" +
"sqrt(81): " + Math.sqrt(81) + "<br>" +
"abs(-7): " + Math.abs(-7);
</script>
Output (after the script runs)
round: 5
ceil: 5
floor: 4
max of 3, 9, 5: 9
sqrt(81): 9
abs(-7): 7
Random numbers
Multiply Math.random() and round down to get a random whole number in a range. This formula gives a number from min to max, both included:
Example
<p id="demo"></p>
<button id="roll" type="button">Roll a die</button>
<script>
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.getElementById("roll").addEventListener("click", function () {
document.getElementById("demo").textContent = "You rolled: " + randomInt(1, 6);
});
</script>
Output (before clicking; run it in the editor)
Math.random() is fine for games and demos but is not secure. Never use it for passwords or tokens.
Common mistakes
- Doing maths on text from a form without converting it.
- Comparing decimals for exact equality, such as
0.1 + 0.2 === 0.3. - Using
toFixed()and then adding the result as text. - Expecting
Math.random()to ever return exactly 1.
Exercise
Calculate the area of a circle with radius 5 (pi x radius x radius) and show it rounded to 2 decimal places.
Show solution
<p id="demo"></p>
<script>
const radius = 5;
const area = Math.PI * radius * radius;
document.getElementById("demo").textContent = "Area: " + area.toFixed(2);
</script>
Knowledge check
1. Which method rounds down?
Math.floor()
2. What type does toFixed() return?
A string.
3. Is Math.random() safe for passwords?
No. It is not secure.
Summary
- Convert text with
Number(),parseInt(), andparseFloat(). - Round with
Math.round,ceil, andfloor, and format withtoFixed. - Build random whole numbers with
Math.floor(Math.random() * ...).