JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Numbers


Numbers are one of the most fundamental data types in JavaScript. Almost every real-world application uses numbers in some form, whether it is calculating prices, handling scores, managing dates, tracking user activity, or performing logical comparisons. JavaScript provides a single Number type to handle both whole numbers and decimal values, which makes it flexible but also important to understand clearly. Knowing how JavaScript handles numbers helps you write accurate calculations, avoid unexpected results, and build reliable programs.

In this chapter, you will learn what JavaScript numbers are, how they work, how to use them in calculations, common numeric behaviors, practical examples, common mistakes, best practices, and real-world applications.

What Are Numbers in JavaScript

In JavaScript, all numeric values are represented using the Number data type, except for BigInt which is used for very large integers. This means integers, floating-point numbers, and even special numeric values are all handled under the same type.

Examples of numbers include:

let age = 21;
let percentage = 87.5;
let temperature = -5;

All of these values belong to the same numeric category.

Why JavaScript Numbers Are Important

Numbers are used everywhere in programming. In JavaScript, numbers help you:

  • Perform calculations and arithmetic operations

  • Compare values using conditions

  • Track counts, indexes, and positions

  • Handle prices, discounts, and totals

  • Process data from forms and APIs

Understanding how numbers behave prevents logical errors and improves code accuracy.

Integer and Floating-Point Numbers

JavaScript does not distinguish between integers and floating-point numbers internally. Both are stored as floating-point values using the IEEE 754 standard.

let totalStudents = 30;
let averageMarks = 82.75;

console.log(typeof totalStudents);  // number
console.log(typeof averageMarks);   // number

Even though these values look different, JavaScript treats them the same way.

Basic Arithmetic with Numbers

JavaScript supports standard arithmetic operations.

Addition

let marksAnanya = 85;
let marksRiya = 90;

let totalMarks = marksAnanya + marksRiya;
console.log(totalMarks);

Subtraction

let budget = 5000;
let expense = 1800;

let remaining = budget - expense;
console.log(remaining);

Multiplication

let price = 250;
let quantity = 4;

let totalCost = price * quantity;
console.log(totalCost);

Division

let totalScore = 450;
let subjects = 5;

let average = totalScore / subjects;
console.log(average);

Modulus

The modulus operator returns the remainder.

let totalClasses = 23;
let classesPerWeek = 5;

let remainingClasses = totalClasses % classesPerWeek;
console.log(remainingClasses);

Decimal Precision Issues

One of the most common surprises in JavaScript is decimal precision.

let result = 0.1 + 0.2;
console.log(result); // 0.30000000000000004

This happens because of how floating-point numbers are stored in binary format.

Handling Precision

A common approach is rounding the result.

let fixedResult = (0.1 + 0.2).toFixed(2);
console.log(fixedResult);

Special Numeric Values

JavaScript includes some special numeric values that behave differently.

Infinity

let largeValue = 10 / 0;
console.log(largeValue); // Infinity

Negative Infinity

let smallValue = -10 / 0;
console.log(smallValue); // -Infinity

NaN

NaN stands for Not a Number and represents an invalid numeric operation.

let value = "Ananya" / 5;
console.log(value); // NaN

Even though it means not a number, its type is still number.

console.log(typeof NaN); // number

Checking Numeric Values

JavaScript provides ways to check whether a value is a valid number.

let score = 90;
let name = "Riya";

console.log(isNaN(score)); // false
console.log(isNaN(name));  // true

This is useful when handling user input.

Numbers from Strings

JavaScript often receives numbers as strings from forms or APIs.

let inputAge = "22";
let age = Number(inputAge);

console.log(age);
console.log(typeof age);

If conversion fails, the result becomes NaN.

let invalidInput = "twenty";
let result = Number(invalidInput);
console.log(result); // NaN

Practical Examples

Example 1: Student Average Calculation

let marksSanya = 78;
let marksIshita = 85;
let marksMira = 92;

let total = marksSanya + marksIshita + marksMira;
let average = total / 3;

console.log("Average Marks: " + average);

Example 2: Shopping Cart Total

let itemPrice = 499;
let itemCount = 3;

let cartTotal = itemPrice * itemCount;
console.log("Total Amount: " + cartTotal);

Example 3: Attendance Percentage

let attendedClasses = 42;
let totalClasses = 50;

let attendance = (attendedClasses / totalClasses) * 100;
console.log("Attendance: " + attendance + "%");

Example 4: Loop with Numbers

for (let day = 1; day <= 7; day++) {
    console.log("Day " + day);
}

Example 5: Discount Calculation

let originalPrice = 2000;
let discountPercent = 10;

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

console.log("Final Price: " + finalPrice);

Common Mistakes

  • Assuming JavaScript separates integers and decimals

  • Ignoring floating-point precision issues

  • Forgetting to convert string input into numbers

  • Dividing by zero without handling Infinity

  • Treating NaN like a normal value

Best Practices

  • Always validate numeric input from users

  • Convert strings to numbers before calculations

  • Use rounding methods when dealing with decimals

  • Check for NaN in calculations

  • Write clear variable names for numeric values

Real-World Applications

JavaScript numbers are used in almost every application:

  • Calculating totals in e-commerce websites

  • Managing scores and rankings in applications

  • Handling timers, counters, and animations

  • Processing financial data and reports

  • Performing logical comparisons and conditions

Summary of JS Numbers

JavaScript numbers form the backbone of calculations and logic in web applications. With a single Number type, JavaScript handles integers, decimals, and special numeric values like Infinity and NaN. While this simplicity is powerful, it also requires careful handling of precision, conversion, and validation. By understanding how numbers behave and following best practices, you can write accurate, reliable, and efficient JavaScript code that works correctly in real-world scenarios.


Practice Questions

Q1. How do you declare a floating-point number 3.14 and store it in a variable pi?

Q2. How do you convert the string "45" into a number using the Number() function?

Q3. What is the output of (10).toFixed(2) and what does it represent?

Q4. How do you check if 25.0 is an integer using Number.isInteger()?

Q5. What is the result of typeof NaN and how is it interpreted in JavaScript?

Q6. How do you write the number 5000 using exponential notation?

Q7. How do you convert 255 into a hexadecimal string using toString()?

Q8. How do you find the largest number representable in JavaScript?

Q9. How do you check whether the result of "abc" - 5 is NaN?

Q10. How do you safely convert a decimal number like "3.14159" to a float?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top