14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2 ■ Data <strong>and</strong> Decisions<br />

You call the methods of the Math object using the following format:<br />

Math.methodOfMathObject( aNumber ):<br />

alert( "The value of pi is " + Math.PI );<br />

We’ll look at a few of the commonly used methods next. (You can find a complete reference by running a<br />

search at https://developer.mozilla.org/en-US/docs/Web_Development.) We’ll look at the methods for rounding<br />

numbers <strong>and</strong> generating r<strong>and</strong>om numbers here.<br />

Rounding Numbers<br />

You saw earlier that the parseInt() function will make a fractional number whole by removing everything after the<br />

decimal point (so 24.999 becomes 24). Pretty often, you’ll want more mathematically accurate calculations—if you’re<br />

working <strong>with</strong> financial calculations, for example—<strong>and</strong> for these, you can use one of the Math object’s three rounding<br />

functions: round(), ceil(), <strong>and</strong> floor(). This is how they work:<br />

• round(): Rounds a number up when the decimal is . 5 or greater<br />

• ceil()(as in ceiling): Always rounds up, so 23.75 becomes 24, as does 23.25<br />

• floor(): Always rounds down, so 23.75 becomes 23, as does 23.25<br />

Here they are at work in a simple example:<br />

<br />

<br />

<br />

var numberToRound = prompt( "Please enter a number", "" )<br />

document.write( "round( ) = " + Math.round( numberToRound ) );<br />

document.write( "" );<br />

document.write( "floor( ) = " + Math.floor( numberToRound ) );<br />

document.write( "" );<br />

document.write( "ceil( ) = " + Math.ceil( numberToRound ) );<br />

<br />

<br />

<br />

Even though you used prompt() to obtain a value from the user, which as you saw earlier returns a string, the<br />

number returned is still treated as a number. This is because the rounding methods do the conversion for you as long<br />

as the string contains something that can be converted to a number.<br />

If you enter 23.75, you get the following result:<br />

round() = 24<br />

floor() = 23<br />

ceil() = 24<br />

If you enter –23.75, you get<br />

round() = -24<br />

floor() = -24<br />

ceil() = -23<br />

30<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!