agyanadda@gmail.com

JS Numbers and Math

Strings and Numbers 1 min read Updated Dec 1, 2026 Topic 11 of 38

JavaScript has one number type for both whole numbers and decimals.

Useful number methods

  • (3.14159).toFixed(2) → '3.14' (string)
  • Number.isInteger(5) → true
  • NaN means "Not a Number", e.g. 'abc' * 2
  • Number.isNaN(value) checks for NaN

The Math object

Method Result
Math.round(4.6) 5
Math.floor(4.9) 4
Math.ceil(4.1) 5
Math.max(2, 9, 4) 9
Math.min(2, 9, 4) 2
Math.abs(-7) 7
Math.sqrt(16) 4
Math.random() random number from 0 to below 1

Random whole number from 1 to 6

Math.floor(Math.random() * 6) + 1

Decimal surprise

0.1 + 0.2 gives 0.30000000000000004. Use toFixed() when showing money.

Example

Example — Dice roller HTML
<button onclick="roll()">Roll the dice</button>
<h2 id="dice">?</h2>
<p id="info"></p>

<script>
  function roll() {
    const n = Math.floor(Math.random() * 6) + 1;
    document.getElementById('dice').textContent = n;
  }
  document.getElementById('info').textContent =
    'Price with GST: ₹' + (499 * 1.18).toFixed(2);
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does Math.floor(7.8) return?

Exercise 2 True / False

Math.random() can return exactly 1.

Exercise 3 Fill in the Blank

NaN stands for Not a ___.

Frequently Asked Questions

Use (100000).toLocaleString('en-IN'), which gives '1,00,000'.