Skip to main content
JavaScript Basics
CHAPTER 13 Beginner

JavaScript Numbers and Math

Updated: May 12, 2026
15 min read

# JavaScript Numbers and Math

Numbers are at the core of almost every application. Whether you are building an e-commerce shopping cart, a game score tracker, or a weather app, you need to handle numbers accurately.

In this chapter, we will learn the nuances of JavaScript numbers and explore the built-in Math object to perform powerful calculations.

1. Introduction

Unlike other programming languages like C or Java, which have different data types for integers (whole numbers) and floats (decimals), JavaScript has only one data type for numbers: Number.

JavaScript also provides a global Math object, which acts like a built-in scientific calculator loaded with functions for rounding, generating random numbers, and finding minimums or maximums.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Understand how JavaScript handles Numbers.
  • Convert Strings to Numbers safely.
  • Format decimal numbers for display using toFixed().
  • Use Math.round(), Math.ceil(), and Math.floor() to round numbers.
  • Generate random numbers using Math.random().
  • Build a Random Password Generator mini-project.

3. JavaScript Numbers Basics

Numbers can be written with or without decimals.

javascript
123
// Example
let x = 34.00; // A number with decimals
let y = 34;    // A number without decimals

The NaN Concept

NaN stands for Not a Number. It is a reserved word indicating that a number is not a legal number. If you try to do math with a string, you will often get NaN.
javascript
123
// Example
let result = 100 / "Apple";
console.log(result); // Output: NaN

4. Number Methods

These methods are called directly on a number variable.

  • toString(): Returns a number as a string.
  • toFixed(): Returns a string, with the number written with a specified number of decimals (perfect for money).
  • Number(): Converts a JavaScript variable (like a string) into a strict Number.

5. The Math Object

The Math object allows you to perform mathematical tasks on numbers. Unlike other objects, Math is static, meaning you do not have to create it. You just use Math.methodName().

---

6. Real-world Examples & Code Snippets

Example 1: toFixed() for Currency

When calculating tax, you often get long decimals. You need to format it to 2 decimal places for currency.

javascript
1234567
// Example JavaScript
let price = 9.99;
let tax = 0.07;
let total = price + (price * tax);

console.log(total); // Output: 10.6893
console.log(total.toFixed(2)); // Output: 10.69 (Rounded beautifully as a String)

Example 2: Converting Strings to Numbers

Data from HTML inputs is ALWAYS a String. You must convert it before doing math.

javascript
1234567
// Example JavaScript
let input1 = "10";
let input2 = "5.5";

console.log(Number(input1) + Number(input2)); // Output: 15.5
console.log(parseInt(input1));   // Output: 10 (forces integer)
console.log(parseFloat(input2)); // Output: 5.5 (keeps decimals)

Example 3: Math.round()

Rounds a number to the nearest integer. .5 rounds UP.

javascript
123
// Example JavaScript
console.log(Math.round(4.6)); // Output: 5
console.log(Math.round(4.4)); // Output: 4

Example 4: Math.ceil()

Ceil (Ceiling) always rounds a number UP to its nearest integer, regardless of the decimal.

javascript
123
// Example JavaScript
console.log(Math.ceil(4.1)); // Output: 5
console.log(Math.ceil(4.9)); // Output: 5

Example 5: Math.floor()

Floor always rounds a number DOWN to its nearest integer.

javascript
123
// Example JavaScript
console.log(Math.floor(4.9)); // Output: 4
console.log(Math.floor(4.1)); // Output: 4

Example 6: Math.max() and Math.min()

Finds the highest or lowest value in a list of arguments.

javascript
123456
// Example JavaScript
let highestScore = Math.max(0, 150, 30, 20, -8, 200);
let lowestScore = Math.min(0, 150, 30, 20, -8, 200);

console.log(highestScore); // Output: 200
console.log(lowestScore);  // Output: -8

Example 7: Math.random()

Math.random() returns a random decimal number between 0 (inclusive) and 1 (exclusive). It will NEVER return exactly 1.

javascript
12
// Example JavaScript
console.log(Math.random()); // Output: 0.8234857... or 0.123512...

Example 8: Creating a Random Integer (The Formula)

Because Math.random() returns a decimal, we must combine it with Math.floor() and multiplication to get useful whole numbers (like rolling a dice).

Formula: Math.floor(Math.random() * max)

javascript
12345678
// Example JavaScript
// Generate a random number between 0 and 9
let randNum = Math.floor(Math.random() * 10);
console.log(randNum);

// Generate a random number between 1 and 10 (Like a 10-sided dice)
let diceRoll = Math.floor(Math.random() * 10) + 1;
console.log(diceRoll);

Example 9: Exponents and Square Roots

javascript
123
// Example JavaScript
console.log(Math.pow(8, 2)); // 8 to the power of 2 (8 * 8). Output: 64
console.log(Math.sqrt(64));  // Square root of 64. Output: 8

Example 10: The Floating Point Precision Bug

Because of how computers store decimals in binary, floating-point math is not always 100% accurate!

javascript
123
// Example JavaScript
let x = 0.2 + 0.1;
console.log(x); // Output: 0.30000000000000004

*Fix: Multiply to integers, do the math, then divide back.*

javascript
12
let fixed = (0.2 * 10 + 0.1 * 10) / 10;
console.log(fixed); // Output: 0.3

---

7. Common Mistakes for Beginners

  1. 1. Using parseInt() for money: parseInt("19.99") will chop off the decimal and return 19. Money is lost! Use parseFloat() or Number() instead.
  1. 2. Forgetting Math.floor() with random: Just doing Math.random() * 10 will give you numbers like 4.827364. If you want a whole number, you must wrap it in Math.floor().
  1. 3. Misunderstanding toFixed(): toFixed() returns a STRING, not a number. If you try to add to it later, it will concatenate instead of do math!

8. Best Practices

  • Always use Number() to convert form inputs before doing calculations.
  • Use toFixed(2) at the very last moment before displaying currency to the user. Do all your math with raw numbers first.
  • If you need a random integer between a min and max, use this standard industry formula:
Math.floor(Math.random() * (max - min + 1) ) + min;

9. Mini Project: Random Password Generator

Let's use Math.random() to generate a secure 8-character password from an array of characters.

HTML:

html
12345678910111213141516171819202122
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        .gen-box { font-family: monospace; border: 2px solid #333; padding: 20px; width: 300px; text-align: center; }
        button { background: #333; color: white; padding: 10px; cursor: pointer; border: none; font-family: monospace;}
        #passOutput { font-size: 24px; font-weight: bold; margin-top: 15px; letter-spacing: 2px;}
    </style>
</head>
<body>

    <div class="gen-box">
        <h3>Password Generator</h3>
        <button onclick="generatePass()">Generate</button>
        <div id="passOutput">********</div>
    </div>

    <script src="password.js"></script>
</body>
</html>

password.js:

javascript
12345678910111213141516171819
// Example JavaScript
function generatePass() {
    // 1. Define all possible characters
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
    let password = "";
    const passwordLength = 8; // We want an 8 character password

    // 2. Loop 8 times
    for (let i = 0; i < passwordLength; i++) {
        // Generate a random index between 0 and the length of the string
        let randomIndex = Math.floor(Math.random() * chars.length);
        
        // Grab the character at that random index and add it to our password
        password += chars[randomIndex];
    }

    // 3. Output to DOM
    document.getElementById("passOutput").innerHTML = password;
}

10. Exercises

  1. 1. Create a variable let num = 5.8;. Console log the result of rounding this number to the nearest integer.
  1. 2. Console log the result of forcing num to round DOWN (floor).
  1. 3. Write a single line of code that generates a random whole number between 1 and 100.

11. MCQs (Multiple Choice Questions)

Q1: What does NaN stand for? A) Not a Null B) Number after Nine C) Not a Number D) Null and None *Answer: C*

Q2: Which method always rounds a number UP? A) Math.round() B) Math.ceil() C) Math.floor() D) Math.up() *Answer: B*

Q3: What data type does the toFixed() method return? A) Float B) Integer C) Array D) String *Answer: D*

12. Interview Questions

Q: Why does 0.1 + 0.2 not equal exactly 0.3 in JavaScript? *A: This is due to the IEEE 754 standard for floating-point arithmetic. Computers represent decimals in binary fractions, and numbers like 0.1 and 0.2 cannot be represented precisely in binary, leading to tiny rounding errors.*

Q: Explain the difference between parseInt(), parseFloat(), and Number(). *A: parseInt() parses a string and returns a whole integer (stopping at the first non-numeric character or decimal). parseFloat() parses a string and returns a number including decimals. Number() strictly converts the entire value into a Number type, returning NaN if it cannot perfectly convert the whole string.*

13. FAQs

Q: Is Math.random() cryptographically secure? *A: No. Math.random() is fine for UI tricks, games, or simple generators. For security-sensitive applications (like generating cryptographic keys), you must use the Web Crypto API (window.crypto.getRandomValues).*

14. Summary

  • JS has only one Number type.
  • Use Number() or parseFloat() to convert strings to numbers for math.
  • Use toFixed() to format money for display.
  • Math.round() (nearest), Math.ceil() (up), and Math.floor() (down) are used for rounding.
  • Math.random() combined with Math.floor() is the standard way to generate random integers.

15. Next Chapter Recommendation

Numbers and Math govern the logic of our apps. But what governs the passage of time? In the next chapter, JavaScript Dates and Time, we will learn how to get the current time, format dates, and build digital clocks.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·