HTML tutorials for the rest of us...
Javascript Tutor - Lesson 18


Javascript has a "Math" object. It is used whenever we want to do anything more than simple arithmetic. It's basic syntax is Math.method(number). I know that's a little confusing at first, but bear with me.

Look at this simple script that calculates square root...


<script type="text/javascript">

function mySquareRoot()
   mynumber = Math.sqrt(9);



<a href="javascript:mySquareRoot()">Click here</a>


Try it.

See what's going on here? It's not too hard at all.

Exercise: Alter the last example to throw up a prompt box that requests a number. Calculate the square root then throw an alert box up that says something like "The square root of 9 is 3"

Here is a solution.

Here's another Math method... Math.round()

It... uh... rounds a number to the nearest integer. (Aren't you glad you got me around to explain things?)

Exercise: Modify the last exercise to throw up a prompt box asking for a number, then round it, then throw up an alert box with the rounded number.

Here is a solution.

Exercise: Combine the last two exercises to get the square root of a number then present it in rounded form. Then, and this is a little tough, determine if the number has in fact been rounded and give a different message depending on whether it's rounded or not. Let me explain further. The square root of 9 rounded is 3. It's exactly 3. The square root of 10 is 3.3333... The square root of 10 rounded is around 3. So, I want you to alter the function so that if the user enters 9 it says...

The square root of 9 is exactly 3.

If the user enters 10 I want it to say...

The square root of 10 rounds to about 3.

You are going to have to do two things. One, find a way to determine if it rounds evenly or not. And two, you're going to have to stick an if-else statement in there to deal with the two possible outputs. Good luck and persevere until you figure it out.

Here is a solution.

There are other Math methods...

Math.floor() rounds down. Math.floor(3.2) is 3. Math.floor(3.9) is 3.

Math.ceil() rounds up. Math.ceil(3.2) is 4. Math.ceil(3.9) is 4.

Math.round() by the way would round anything less than 3.5 to 3, and 3.5 or greater to 4.

How to round to the nearest tenth? Quite simple really... multiply a number by 10, round it, then divide by 10.

Try it.

There is Math.sin(), Math.cos(), etc. There is Math.max(). (Hey, wasn't that a movie with Mel Gibson?)

Math.max(x,y) returns the greater of two numbers while Math.min(x,y) returns the lesser.

Math.max(2,8) returns 8 and Math.min(2,8) returns 2.

There are a few others, and especially if you're a math person, I encourage you to study further.

Javascript Tutor
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Javascript Authoring Guide      JavaScript FAQ
HTML 4.0 Reference      Google Groups (Advanced Search)