JavaScript has one number type for both whole numbers and decimals.
Useful number methods
(3.14159).toFixed(2)→'3.14'(string)Number.isInteger(5)→trueNaNmeans "Not a Number", e.g.'abc' * 2Number.isNaN(value)checks for NaN
The Math object
| Method | Result |
|---|---|
Math.round(4.6) |
5 |
Math.floor(4.9) |
4 |
Math.ceil(4.1) |
5 |
Math.max(2, 9, 4) |
9 |
Math.min(2, 9, 4) |
2 |
Math.abs(-7) |
7 |
Math.sqrt(16) |
4 |
Math.random() |
random number from 0 to below 1 |
Random whole number from 1 to 6
Math.floor(Math.random() * 6) + 1
Decimal surprise
0.1 + 0.2 gives 0.30000000000000004. Use toFixed() when showing money.
Example
Example — Dice roller
HTML
<button onclick="roll()">Roll the dice</button>
<h2 id="dice">?</h2>
<p id="info"></p>
<script>
function roll() {
const n = Math.floor(Math.random() * 6) + 1;
document.getElementById('dice').textContent = n;
}
document.getElementById('info').textContent =
'Price with GST: ₹' + (499 * 1.18).toFixed(2);
</script>