SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
JavaScript
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10
Try this code live
Lesson 18 of 35

JavaScript Math Object — random, round, floor, ceil

5 min read · Free · No login needed

JavaScript's Math object is a toolbox for numbers. It has no constructor — you never write new Math(). You just call its methods: Math.random() for a lucky draw, Math.round() to tidy a decimal, Math.max() to find the biggest number in a list. Every quiz app, every discount calculator and every game uses it.

Diagram — see how it fits together
Diagram: JavaScript Math

Think of a cricket match. The umpire tosses a coin — that is Math.random(). The scorer rounds a run-rate of 7.63 to 8 — that is Math.round(). The captain picks the highest score of the day — that is Math.max(). One object, many small jobs, and each method does exactly one thing.

Remember it like this: random gives, round tidies, floor drops, ceil lifts, max picks biggest, min picks smallest.

Math.random — a number from nowhere

Math.random() returns a decimal number from 0 up to (but never including) 1 — something like 0.483921. On its own it is not very useful, so you usually stretch it to the range you want. To get a whole number from 1 to 6, like a dice roll, you multiply by 6, drop the decimal, and add 1.

let dice = Math.floor(Math.random() * 6) + 1;
// A whole number from 1 to 6

Read it inside out: Math.random() gives 0 to 0.999..., times 6 gives 0 to 5.999..., Math.floor() drops the decimal to give 0 to 5, and adding 1 gives 1 to 6. Every time the page runs, you get a different number — that is the whole point.

Math.round, Math.floor, Math.ceil — tidying decimals

These three all turn a decimal into a whole number, but in different ways. Math.round() rounds to the nearest whole number: 4.5 becomes 5, 4.4 becomes 4. Math.floor() always rounds down: 4.9 becomes 4. Math.ceil() always rounds up: 4.1 becomes 5.

Math.round(4.5); // 5
Math.round(4.4); // 4
Math.floor(4.9); // 4
Math.ceil(4.1);  // 5
Note: Floor means the ground — the number falls down to the whole number below it. Ceil means the ceiling — the number rises up to the whole number above it. Picture the words and you will never mix them up: floor is down, ceil is up.

When would you use each one? Math.round() is for bills and averages, where nearest is fairest. Math.floor() is for counting whole things — how many full boxes fit, how many complete pages. Math.ceil() is for "how many do I need?" — if 4.1 buses are needed, you need 5 buses, not 4.

Math.max and Math.min — biggest and smallest

Math.max() returns the biggest of the numbers you give it, and Math.min() returns the smallest. You can pass as many numbers as you like, separated by commas.

let scores = [45, 82, 30, 91, 67];
Math.max(45, 82, 30, 91, 67); // 91
Math.min(45, 82, 30, 91, 67); // 30

But what if the numbers are already inside an array? Math.max(scores) does not work — it returns NaN, because the method expects separate numbers, not one array. The fix is the spread operator, three dots, which unpacks the array into separate numbers: Math.max(...scores) gives 91. You will meet the spread operator properly later; for now, just remember the three dots.

Tip: Math.random() is not truly random — it is pseudo-random, good enough for games, quizzes and lucky draws, but never use it for passwords or security. For a classroom dice or a lucky-draw winner, it is perfect.

Common mistakes

  • Writing new Math() — Math is not a constructor. There is no new here; you call Math.round() directly.
  • Expecting Math.random() to give a whole number — it always gives a decimal from 0 to just under 1. Multiply and floor it to get a whole number.
  • Using Math.max() on an array directly — it returns NaN. Spread the array first: Math.max(...scores).
  • Mixing up Math.floor() and Math.ceil() — floor goes down, ceil goes up. Remember the floor and the ceiling.
  • Forgetting that Math.round(4.5) is 5 but Math.round(-4.5) is -4 — rounding negative numbers goes towards positive infinity, not away from zero.

Remember

  • Random gives, round tidies, floor drops, ceil lifts, max picks biggest, min picks smallest.
  • A dice roll is Math.floor(Math.random() * 6) + 1 — random, stretch, drop the decimal, add 1.
  • Math.max(...array) and Math.min(...array) work on arrays; without the three dots they return NaN.
  • Never write new Math() — Math is used directly, with no constructor.

Example explained

  • Math.floor(Math.random() * 6) + 1 — rolls a dice: a random decimal, stretched to 0–5.999, floored to 0–5, then plus 1 gives 1–6.
  • Math.max(...scores) — the three dots unpack the scores array, so Math.max sees separate numbers and returns the biggest, 91.
  • Math.min(...scores) — the same trick gives the smallest score, 30.
  • Math.round(82.5) — rounds the average to the nearest whole number.
  • document.getElementById("result").innerHTML = ... — writes the dice roll and the highest and lowest scores into the page when the button is clicked.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Dice Roll — JavaScript Math</title>
<style>
body { font-family: Verdana, sans-serif; padding: 20px; }
h1 { color: #1e3a5f; }
button { background-color: #e13611; color: white; border: none; padding: 10px 18px; font-size: 16px; cursor: pointer; }
p { font-size: 18px; }
.result { background-color: #f1f5f9; padding: 12px; }
.dice { font-size: 48px; }
</style>
</head>
<body>

<h1>Dice Roll and Top Score</h1>
<p>Scores: 45, 82, 30, 91, 67</p>
<button onclick="rollDice()">Roll the Dice</button>
<p class="dice" id="dice">🎲</p>
<p class="result" id="result">Click the button to roll the dice and see the highest and lowest scores.</p>

<script>
function rollDice() {
  let dice = Math.floor(Math.random() * 6) + 1;
  let scores = [45, 82, 30, 91, 67];
  let highest = Math.max(...scores);
  let lowest = Math.min(...scores);
  let average = Math.round(315 / 5);
  document.getElementById("dice").innerHTML = "🎲 " + dice;
  document.getElementById("result").innerHTML =
    "You rolled: " + dice +
    "<br>Highest score: " + highest +
    "<br>Lowest score: " + lowest +
    "<br>Average (rounded): " + average;
}
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript Math Object — random, round, floor, ceil

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Frequently asked questions

The questions learners ask most about this lesson — read the question, then open it to see the answer.

1. How do I get a random whole number from 1 to 6?

Use Math.floor(Math.random() * 6) + 1: random gives 0 to 0.999, times 6, floored, plus 1.

2. What is the difference between Math.floor and Math.ceil?

Floor drops the decimal down and ceil lifts it up; round tidies to the nearest whole number.

3. Can I write new Math()?

No. Math has no constructor — you just call its methods like Math.random() and Math.max() directly.

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 35 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

Ethical Hacking & Cyber Security Workshop
View
AI Power Skills in 2 Days | Learn AI Text, Image, Video and Voice Tools
View
Core Python Programming – 3 Month Complete Course
₹700
View
Browse all courses
JavaScript — Lessons
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Please log in to download. You will stay on this page after logging in!

New here? Register now →