iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ConstantValue
Number.MAX_SAFE_INTEGER2⁵³ − 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 / -InfinityOverflow / 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

FromToUse
StringIntegerparseInt(s, 10) or Number(s) or +s
StringFloatparseFloat(s)
NumberStringString(n) or n.toString() or `${n}`
FloatFixed 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, );

Test yourself

Q1. `0.1 + 0.2 === 0.3` is…
Q2. The safest integer max is…
Q3. Convert a string to integer with…

Discussion

Loading…