Working with Numbers

Course: JavaScript Beginner

Lesson 5: Working with Numbers

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Perform arithmetic in JavaScript using standard operators
  • Use Math methods for rounding, finding maximums, and generating random numbers
  • Convert strings to numbers using parseInt and parseFloat, and recognize NaN

Frontend Development Context

Numbers show up constantly in frontend work — item counts, prices, star ratings, progress percentages, scroll positions, and animation durations are all numeric values your code needs to read, calculate, and display. Getting arithmetic right and knowing how to convert between number formats is a daily necessity, not an edge case.

JavaScript has some surprising number behaviors that catch beginners off guard — floating point imprecision, the mysterious NaN, and the way form inputs return strings instead of numbers. Understanding these behaviors early means fewer head-scratching bugs when your price calculation shows 0.30000000000000004 or your button counter stops working because you forgot to convert the input first.

Explanation

JavaScript uses a single number type for all numeric values — integers, decimals, and everything in between. The basic arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo, which gives the remainder of division). These work as you would expect for most cases.

The Math object provides a collection of useful mathematical methods. Math.round(n) rounds to the nearest integer. Math.floor(n) rounds down. Math.ceil(n) rounds up. Math.max(a, b) returns the larger of two values. Math.min(a, b) returns the smaller. Math.random() returns a random decimal between 0 (inclusive) and 1 (exclusive) — multiply and floor it to get a random integer in a range.

parseInt(string, radix) converts a string to an integer. The second argument is the base (almost always 10 for decimal numbers). parseFloat(string) converts a string to a decimal number. Both functions read as many characters as they can and stop at the first non-numeric character, which means parseInt("42px", 10) returns 42.

NaN stands for "Not a Number". It is what JavaScript returns when a numeric operation cannot produce a meaningful result — for example, parseInt("hello", 10) or 0 / 0. The strange thing about NaN is that it is not equal to itself: NaN === NaN is false. To check if a value is NaN, use Number.isNaN(value).

JavaScript's floating-point arithmetic follows the IEEE 754 standard, which causes small precision errors with decimal math. 0.1 + 0.2 does not equal 0.3 exactly in JavaScript — it gives 0.30000000000000004. For displaying prices or percentages, round to a fixed number of decimal places using .toFixed(2) on the number.

Code Example

This example calculates a discounted price and displays it formatted for the UI:

const originalPrice = 49.99;
const discountPercent = 15;

const discountAmount = (originalPrice * discountPercent) / 100;
const finalPrice = originalPrice - discountAmount;

// Round to 2 decimal places for display
const displayPrice = finalPrice.toFixed(2);

const savings = Math.round(discountAmount * 100) / 100;

document.querySelector("#price").textContent = `$${displayPrice}`;
document.querySelector("#savings").textContent = `You save $${savings}`;

console.log(Number.isNaN(finalPrice)); // false
console.log(parseInt("42px", 10));     // 42

Code Explanation

The discount is calculated as a percentage of the original price using standard arithmetic. Dividing by 100 converts the percentage (15) into a decimal multiplier (0.15), then multiplying by the price gives the discount amount.

finalPrice.toFixed(2) converts the number to a string with exactly 2 decimal places. This is essential for currency display — without it, floating-point arithmetic might produce something like 42.4914999... instead of 42.49.

Math.round(discountAmount * 100) / 100 is a common pattern for rounding to 2 decimal places without converting to a string. Multiply by 100 to move the decimal, round to the nearest integer, then divide by 100 to move it back.

The Number.isNaN check at the end shows how to verify a calculation produced a real number. The parseInt("42px", 10) example demonstrates that parseInt gracefully handles strings that start with a number followed by units — useful when reading values like "16px" from CSS.

Pattern Highlights

Positive Pattern: Use .toFixed(2) when displaying prices and percentages to ensure consistent decimal formatting in the UI, even if the raw number has floating-point imprecision.

⚠️ Neutral Note: Math.random() is not cryptographically secure. Do not use it for security-sensitive features. For display purposes and UI features, it is perfectly fine.

Negative Pattern: Adding a number to a string from a form input produces string concatenation, not arithmetic. Always convert form values with Number() or parseInt() before doing math on them.

Common Mistakes

Mistake 1: Using form input values directly in arithmetic

Form .value always returns a string, even when the user types a number. Adding it to another number concatenates instead of adding.

const input = document.querySelector("#quantity").value; // "3" (string)
const total = input + 10; // "310" — string concatenation!

// Correct:
const total2 = Number(input) + 10; // 13

Always convert input values with Number(), parseInt(), or parseFloat() before performing arithmetic.

Mistake 2: Comparing with NaN using ===

NaN is the only value in JavaScript that is not equal to itself, so === NaN always returns false.

const result = parseInt("not a number", 10);
console.log(result === NaN); // false — always false, even when result IS NaN

// Correct:
console.log(Number.isNaN(result)); // true

Always use Number.isNaN() to check for NaN, never === NaN.

Mistake 3: Displaying raw floating-point results to users

Floating-point arithmetic in JavaScript can produce long decimal strings that look wrong to users.

const price = 0.1 + 0.2;
document.querySelector("#total").textContent = price; // "0.30000000000000004"

// Correct:
document.querySelector("#total").textContent = price.toFixed(2); // "0.30"

Use .toFixed(n) when displaying numbers that users will read, especially monetary amounts.

Quick Recap

  • JavaScript uses one number type for integers and decimals; arithmetic uses +, -, *, /, and %
  • The Math object provides round, floor, ceil, max, min, and random among others
  • parseInt(string, 10) and parseFloat(string) convert strings to numbers; form .value is always a string
  • NaN means "Not a Number" — check for it with Number.isNaN(), and use .toFixed(2) when displaying decimal values

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01