JS Numbers
JavaScript has one numeric type: number, a 64-bit float (IEEE 754). It handles integers and decimals, plus the special values NaN and Infinity.
Edges of the number type
| Constant | Value |
|---|---|
Number.MAX_SAFE_INTEGER | 2⁵³ − 1 = 9,007,199,254,740,991 |
Number.MIN_SAFE_INTEGER | −(2⁵³ − 1) |
Number.MAX_VALUE | ~1.79e308 |
Number.EPSILON | ~2.22e-16 — the smallest difference between two floats |
Infinity / -Infinity | Overflow / divide by 0 |
NaN | "Not a Number" — result of invalid math like 0/0 |
Float precision
JS
0.1 + 0.2 === 0.3 // false — classic float-rounding 0.1 + 0.2 // 0.30000000000000004 // Work around it Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON // true (0.1 + 0.2).toFixed(1) === "0.3" // true
Useful conversions
| From | To | Use |
|---|---|---|
| String | Integer | parseInt(s, 10) or Number(s) or +s |
| String | Float | parseFloat(s) |
| Number | String | String(n) or n.toString() or `${n}` |
| Float | Fixed digits | (1/3).toFixed(2) → "0.33" |
Tip: Money should never be stored as a float. Use integer cents (
amount: 1099) or a dedicated decimal library. The 0.1 + 0.2 bug becomes a real bug when you bill someone.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Numbers!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Parse a base-10 integer from a string.
const n = parseInt(s,
);
Always pass an explicit radix.
Discussion
Loading…