javascript-course-chapter-09
Chapter 9: Numbers and Math
Learn JavaScript numbers, math methods, rounding, random numbers, precision, Infinity, NaN, BigInt, and calculations.
Goal: Understand how JavaScript works with numbers and how to use math safely in real projects.
9.1 Number Methods
Number methods are built-in tools that help you format and convert numbers.
They are very useful when showing prices, scores, percentages, and measurements.
For example, you can control decimal places with toFixed().
You can convert a number into text with toString().
You can also make numbers easier to display for users.
Beginners should learn these methods because numbers are used in almost every real app.
Example: Format a price with toFixed()
// Store a price with many decimal places.
let price = 19.9876;
// toFixed(2) keeps only 2 digits after the decimal point.
// This is useful for money and prices.
let formattedPrice = price.toFixed(2);
// Print the formatted price.
console.log(formattedPrice);
// Output:
// 19.99
Code Explanation:
The original number has four decimal digits.
toFixed(2) rounds the number and displays two decimal places.
The output becomes useful for showing money.
9.2 Math Object
The Math object gives JavaScript many ready-made math tools.
You do not need to create Math yourself because it already exists.
You can use it for square roots, maximum values, minimum values, powers, random numbers, and rounding.
Math methods are written like Math.max() or Math.sqrt().
This is helpful when building calculators, games, charts, and learning apps.
The Math object saves time because JavaScript already provides common math operations.
Example: Use Math.max(), Math.min(), and Math.sqrt()
// Math.max() finds the biggest number.
console.log(Math.max(10, 25, 5));
// Math.min() finds the smallest number.
console.log(Math.min(10, 25, 5));
// Math.sqrt() finds the square root.
console.log(Math.sqrt(81));
// Output:
// 25
// 5
// 9
Code Explanation:
Math.max() returns the largest value.
Math.min() returns the smallest value.
Math.sqrt(81) returns 9 because 9 × 9 equals 81.
9.3 Random Numbers
Random numbers are numbers chosen by JavaScript in an unpredictable way.
The method Math.random() gives a decimal number from 0 up to less than 1.
Random numbers are useful in games, quizzes, random colors, lottery numbers, and practice apps.
Usually, beginners combine Math.random() with Math.floor().
This allows us to create whole random numbers.
Random values make programs feel more dynamic and interactive.
Example: Random number from 1 to 10
// Math.random() gives a decimal from 0 to less than 1.
// Multiplying by 10 gives a number from 0 to less than 10.
// Math.floor() removes the decimal part.
// Adding 1 makes the range from 1 to 10.
let randomNumber = Math.floor(Math.random() * 10) + 1;
// Print the random number.
console.log(randomNumber);
// Output:
// Any number from 1 to 10
Code Explanation:
Every time you run this code, the answer may be different.
This is why the output says any number from 1 to 10.
This pattern is common in beginner games and quiz apps.
9.4 Rounding
Rounding means changing a decimal number into a cleaner number.
JavaScript has different rounding methods for different needs.
Math.round() rounds to the nearest whole number.
Math.floor() always rounds down.
Math.ceil() always rounds up.
These methods are useful for prices, ratings, pages, scores, and measurements.
Example: Round numbers different ways
// Store a decimal number.
let number = 4.7;
// Math.round() rounds to the nearest whole number.
console.log(Math.round(number));
// Math.floor() rounds down.
console.log(Math.floor(number));
// Math.ceil() rounds up.
console.log(Math.ceil(number));
// Output:
// 5
// 4
// 5
Code Explanation:
4.7 is closer to 5, so Math.round() gives 5.
Math.floor() goes down to 4.
Math.ceil() goes up to 5.
9.5 Precision
Precision means how exact a number is.
JavaScript uses floating-point math for decimal numbers.
Sometimes decimal calculations may look slightly wrong because computers store decimals in binary.
For example, 0.1 + 0.2 may not show exactly 0.3.
This is normal in many programming languages.
Beginners should use rounding methods like toFixed() when showing decimal results to users.
Example: Decimal precision issue
// Add two decimal numbers.
let result = 0.1 + 0.2;
// Print the raw result.
console.log(result);
// Format the result to 2 decimal places.
console.log(result.toFixed(2));
// Output:
// 0.30000000000000004
// 0.30
Code Explanation:
JavaScript stores decimal numbers in a way that can create tiny precision differences.
toFixed(2) makes the result cleaner for display.
This is very useful for money and measurements.
9.6 Infinity
Infinity is a special number value in JavaScript.
It can appear when a number is too large or when dividing by zero.
JavaScript does not always crash when this happens.
Instead, it may return Infinity.
There is also -Infinity for negative infinite values.
Beginners should understand Infinity so they can detect unusual math results.
Example: Divide by zero
// Divide a number by zero.
let result = 10 / 0;
// Print the result.
console.log(result);
// Check the type.
console.log(typeof result);
// Output:
// Infinity
// number
Code Explanation:
JavaScript returns Infinity when 10 is divided by 0.
Infinity is still considered a number type.
You should check for it when doing important calculations.
9.7 NaN
NaN means “Not a Number”.
It appears when JavaScript tries to do a number operation but the result is not a valid number.
For example, dividing text by a number can create NaN.
NaN is a special value, but its type is still number.
Beginners often see NaN when user input is not converted correctly.
You can use Number.isNaN() to check if a result is NaN.
Example: Invalid math gives NaN
// Try to divide text by a number.
let result = "hello" / 2;
// Print the result.
console.log(result);
// Check if the result is NaN.
console.log(Number.isNaN(result));
// Output:
// NaN
// true
Code Explanation:
The word hello cannot be divided by 2.
JavaScript cannot create a valid number answer.
So the result becomes NaN.
9.8 BigInt
BigInt is used for very large whole numbers.
Normal JavaScript numbers have a safe limit.
When numbers become too large, BigInt can store them more safely.
BigInt values end with the letter n.
You cannot mix BigInt and normal Number directly in math.
Beginners should use BigInt only when working with very large integer values.
Example: BigInt calculation
// Create two BigInt values.
// The n at the end means BigInt.
let bigNumber1 = 9007199254740993n;
let bigNumber2 = 10n;
// Add BigInt values together.
let result = bigNumber1 + bigNumber2;
// Print the result.
console.log(result);
// Output:
// 9007199254741003n
Code Explanation:
Both values are BigInt because they end with n.
JavaScript can safely add them as very large integers.
The output also ends with n.
9.9 Scientific Notation
Scientific notation is a short way to write very large or very small numbers.
JavaScript supports this using the letter e.
For example, 1e3 means 1 × 10³, which equals 1000.
This style is common in science, math, engineering, and large data calculations.
It can make code shorter when numbers are very large.
Beginners should recognize it so they are not confused when they see numbers with e.
Example: Scientific notation
// 1e3 means 1 times 10 to the power of 3.
let thousand = 1e3;
// 5e6 means 5 times 10 to the power of 6.
let fiveMillion = 5e6;
// Print both numbers.
console.log(thousand);
console.log(fiveMillion);
// Output:
// 1000
// 5000000
Code Explanation:
The letter e means “times 10 to the power of”.
1e3 becomes 1000.
5e6 becomes 5,000,000.
9.10 Calculations
Calculations combine numbers, operators, variables, and sometimes Math methods.
JavaScript calculations are used in bills, shopping carts, grades, games, budgets, and reports.
You should store values in clear variables before calculating.
This makes your code easier to read and fix.
When working with money, format the final result for users.
Beginners should practice calculations often because they appear in many projects.
Example: Calculate total price with tax
// Store the product price.
let price = 100;
// Store the tax rate.
// 0.13 means 13%.
let taxRate = 0.13;
// Calculate the tax amount.
let taxAmount = price * taxRate;
// Calculate the final total.
let total = price + taxAmount;
// Print the result with 2 decimal places.
console.log(total.toFixed(2));
// Output:
// 113.00
Code Explanation:
The code first calculates the tax by multiplying the price by the tax rate.
Then it adds the tax to the original price.
toFixed(2) displays the final total like money.
Chapter 9 Summary
- Number methods help format and convert numbers.
- The Math object provides ready-made math tools.
- Random numbers are useful for games, quizzes, and dynamic apps.
- Rounding helps clean decimal numbers.
- Precision issues can happen with decimal math.
- Infinity appears in special math cases like dividing by zero.
- NaN means JavaScript could not produce a valid number.
- BigInt stores very large whole numbers.
- Scientific notation writes very large or small numbers in short form.
- Calculations are used in real projects like bills, totals, grades, and budgets.