JavaScript Numbers

Number methods, rounding and NaN.

✍️ 3 exercises + code challenge in this lesson

JavaScript has a single Number type for integers and decimals.

  • toFixed(2): format with 2 decimals (returns a string).
  • Number("42"), parseInt("42px"), parseFloat("3.14"): convert strings to numbers.
  • NaN means "Not a Number"; check with Number.isNaN().
  • Infinity is the result of dividing by zero.
  • Number.isInteger(), Number.MAX_SAFE_INTEGER
Decimal maths can be imprecise: 0.1 + 0.2 is 0.30000000000000004. Round results when displaying money.

Key Takeaways: JavaScript Numbers

Mastering JavaScript Numbers helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Numbers Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const price = 1234.5678;
log(price.toFixed(2));
log(Number("42") + 1, parseInt("42px"), parseFloat("3.14abc"));
log("abc" * 3, Number.isNaN("abc" * 3));
log(10 / 0);
log(0.1 + 0.2, "→", (0.1 + 0.2).toFixed(2));
log(new Intl.NumberFormat("en-PK", { style: "currency", currency: "PKR" }).format(250000));
</script>
Free sign-in required · Google login available

JavaScript Numbers Practice Exercises

Check what you learned in “JavaScript Numbers”.

/ 3 solved
Fill in the blank

Show the number with exactly two decimals.

price.(2)
✓ Correct! Not quite. Try again.
Multiple choice

What does Number("abc") return?

✓ Correct! Not quite. Try again.
Code challenge

Convert the string "42" to a number, add 8 and log the result.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services