Java Reference
In-Depth Information
The round() Method
The round() method is very similar to ceil() and floor(), except that instead of always rounding
up or always rounding down, it rounds up only if the decimal part is .5 or greater, and rounds down
otherwise.
For example:
var myNumber = 44.5;
document.write(Math.round(myNumber) + “<br />”);
myNumber = 44.49;
document.write(Math.round(myNumber));
This code would write the numbers 45 and 44 to the page.
Summary of Rounding Methods
As you have seen, the ceil(), floor(), and round() methods all remove the numbers after a deci-
mal point and return just a whole number. However, which whole number they return depends on the
method used: floor() returns the lowest, ceil() the highest, and round() the nearest equivalent inte-
ger. This can be a little confusing, so the following is a table of values and what whole number would be
returned if these values were passed to the parseInt() function, and ceil(), floor(), and round()
methods.
Parameter
parseInt() returns
ceil() returns
fl oor() returns
round() returns
10.25
10
11
10
10
10.75
10
11
10
11
10.5
10
11
10
11
-10.25
-10
-10
-11
-10
-10.75
-10
-10
-11
-11
-10.5
-10
-10
-11
-10
Remember that parseInt() is a native JavaScript function, not a method of the Math object, like the
other methods presented in this table.
Try It Out Rounding Methods Results Calculator
If you're still not sure about rounding numbers, the following example should help. Here, you'll look at
a calculator that gets a number from the user, and then writes out what the result would be when you
pass that number to parseInt(), ceil(), floor(), and round().
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
Search WWH ::




Custom Search