JavaScript Numbers & Math¶
JavaScript Numbers¶
JavaScript has only one type of number. Numbers can be written with, or without decimals.
Precision Issues¶
Integers are accurate up to 15 digits. Floating point arithmetic is not always 100% accurate:
Fix: To solve this, multiply and divide:let x = (0.2 * 10 + 0.1 * 10) / 10;
NaN - Not a Number¶
NaN is a reserved word indicating that a number is not a legal number.
Number Methods¶
toString(): Returns a number as a string.toFixed(n): Returns a string with the number written withndecimals (e.g.,9.656.toFixed(2)->"9.66").Number(str): Converts a variable to a number.parseInt(str): Parses a string and returns a whole number.
The Math Object¶
The JavaScript Math object allows you to perform mathematical tasks on numbers.
| Method | Description |
|---|---|
Math.round(x) |
Rounds to the nearest integer. |
Math.ceil(x) |
Rounds up to the nearest integer. |
Math.floor(x) |
Rounds down to the nearest integer. |
Math.sqrt(x) |
Returns the square root. |
Math.abs(x) |
Returns the absolute value. |
Math.random() |
Returns a random number between 0 and 1. |
Random Integer
To get a random integer between 0 and 10:
Math.floor(Math.random() * 11);