Module 18 : Math Object and Number Methods
JavaScript Math Object and Number Methods
🔷 Part 1: Math Object
The Math object in JavaScript is a built-in object that has properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor, so you don’t create Math objects.
🔹 Common Math Methods
Method
Description
Example
Math.abs(x)
Returns the absolute (positive) value of x
Math.abs(-4.7) ➝ 4.7
Math.ceil(x)
Rounds x up to the nearest integer
Math.ceil(4.4) ➝ 5
Math.floor(x)
Rounds x down to the nearest integer
Math.floor(4.7) ➝ 4
Math.round(x)
Rounds x to the nearest integer
Math.round(4.5) ➝ 5
Math.max(a, b, …)
Returns the highe
Math.max(1, 5, 10) ➝ 10
st number
Math.min(a, b, …)
Returns the lowest number
Math.min(1, 5, 10) ➝ 1
Math.random()
Returns a pseudo-random number between 0 and 1
Math.random() ➝ 0.234…
Math.pow(x, y)
Returns x to the power of y
Math.pow(2, 3) ➝ 8
Math.sqrt(x)
Returns the square root of x
Math.sqrt(16) ➝ 4
Math.trunc(x)
Returns integer part of x by removing decimals
Math.trunc(4.9) ➝ 4
📘 Example
javascript
code
function calculateAreaOfCircle(radius) { return Math.PI * Math.pow(radius, 2); } console.log(calculateAreaOfCircle(5)); // ➝ 78.53981633974483
🔷 Part 2: Number Methods
JavaScript provides methods that can be used with number values.
🔹 Common Number Methods
Method
Description
Example
toFixed(n)
Formats number with n decimals (returns string)
(12.3456).toFixed(2) ➝ "12.35"
toPrecision(n)
Formats number to n significant digits
(123.456).toPrecision(4) ➝ "123.5"
toString([radix])
Converts number to a string (optional radix)
(255).toString(16) ➝ "ff"
Number.isFinite(x)
Checks if x is a finite number
Number.isFinite(5) ➝ true
Number.isInteger(x)
Checks if x is an integer
Number.isInteger(5.1) ➝ false
Number.parseFloat(x)
Parses a string and returns a floating-point number
Number.parseFloat("10.33") ➝ 10.33
Number.parseInt(x)
Parses a string and returns an integer
Number.parseInt("10.33") ➝ 10
📘 Example
javascript code
function formatCurrency(amount) { return "$" + amount.toFixed(2); } console.log(formatCurrency(9)); // ➝ "$9.00" console.log(formatCurrency(9.567)); // ➝ "$9.57"
🎓 Exercises
🔹 Exercise 1: Generate a Random Integer Between 1 and 100
javascript
code
function getRandomInt1to100() { return Math.floor(Math.random() * 100) + 1; } console.log(getRandomInt1to100());
🔹 Exercise 2: Format and Validate a User Input
javascript
code
function validateAndFormat(input) { let num = Number.parseFloat(input); if (Number.isFinite(num)) { return num.toFixed(2); } else { return "Invalid number!"; } } console.log(validateAndFormat("123.456")); // ➝ "123.46" console.log(validateAndFormat("abc")); // ➝ "Invalid number!"
🔹 Exercise 3: Find Min and Max from User Input
javascript
code
function findMinMax(...numbers) { return { min: Math.min(...numbers), max: Math.max(...numbers) }; } console.log(findMinMax(4, 8, 1, 99, 0)); // ➝ { min: 0, max: 99 }
🧠 Notes
Math vs. Number:
Math is a namespace with utility functions.
Number methods work on number values or Number objects.
Precision Issues:
JavaScript uses floating-point arithmetic (IEEE 754), which can lead to rounding errors.
Use toFixed() or libraries like BigInt/Decimal.js for high precision needs.
Security Tip:
Never use Math.random() for cryptographic purposes. Use crypto.getRandomValues() in secure contexts.
🧑🏫 Plan
Introduction:
Define Math and Number in JavaScript.
Clarify their differences with diagrams.
Demonstration:
Use live coding tools to show output.
Challenge with edge cases (e.g., Math.floor(-1.5)).
Practice Time:
Divide into groups to build a calculator that uses at least 3 Math and 2 Number methods.
Q&A and Wrap-up:
Discuss common pitfalls.
Hand out a quiz (e.g., "What does parseInt('12.34') return?").
No comments:
Post a Comment