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

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)

MethodReturns
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)

MethodExample
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);

Test yourself

Q1. Convert a number to a hex string with…
Q2. Locale-aware currency formatting uses…
Q3. Safer NaN test is…

Discussion

Loading…