JS Number Methods
JavaScript's Number object provides helpers on the type itself (Number.isFinite), and instance methods on number values ((1.234).toFixed(2)).
Static methods (on Number)
| Method | Returns |
|---|---|
Number(x) | Convert to number, or NaN. |
Number.parseInt(s, radix) | Integer parsed from string. |
Number.parseFloat(s) | Float parsed from string. |
Number.isInteger(x) | True only for integers. |
Number.isFinite(x) | True for real numbers (not NaN/Infinity). |
Number.isNaN(x) | True only for NaN — safer than global isNaN. |
Number.isSafeInteger(x) | True if x is in the ±2⁵³−1 safe range. |
Instance methods (on a number)
| Method | Example |
|---|---|
toString(base?) | (255).toString(16) → "ff" |
toFixed(n) | (3.14159).toFixed(2) → "3.14" |
toPrecision(n) | (123.456).toPrecision(4) → "123.5" |
toExponential(n) | (1500).toExponential(2) → "1.50e+3" |
toLocaleString(locale, opts) | (1234.5).toLocaleString("en-US", { style: "currency", currency: "USD" }) |
Format a price
JS
const price = 1499.5;
price.toFixed(2); // "1499.50"
price.toLocaleString("en-US", { // "$1,499.50"
style: "currency", currency: "USD",
});
new Intl.NumberFormat("de-DE", { // "1.499,50 €"
style: "currency", currency: "EUR",
}).format(price);
Tip: For formatting many numbers in a loop, build the
Intl.NumberFormat once and reuse it — it's faster than calling toLocaleString each time.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Number Methods!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Round a price to two decimal places as a string.
const str = price.
(2);
Seven letters — formatting helper.
Discussion
Loading…