|
Round a Number
By Stephen Bucaro
In some situations, for example when you want to display a number, you may want
to round it to a certain number of decimal places. The Java Script Math
object provides three different methods for rounding numbers.
Math.round
The Math.round method produces the result as we learned it in grammar school.
If the decimal portion of the number is less than .5, it rounds down to the next
lower integer. If the decimal portion of the number is greater than .5, it rounds
up to next higher integer.
The statement Math.round(4.4) returns the value 4.
The statement Math.round(4.5) returns the value 5.
Math.floor
The Math.floor method simply drops the decimal part of the number, this
causes it to always return the next integer less than or equal to the original value.
The statement Math.floor(4.4) returns the value 4.
The statement Math.floor(4.4) returns the value 4.
When would you want to round down? When calculating sales charges you should always
round down to the nearest penny so that the benefit of rounding goes to the customer.
Math.ceil
If the Math.ceil method finds any decimal portion of a number greater
zero, it returns the next integer higher than or equal to value.
The statement Math.ceil(4.4) returns the value 5.
The statement Math.ceil(4.4) returns the value 5.
When would you want to round up? When calculating wages paid to employees or interest
earned by investors you should always round up to the nearest penny so that the benefit
of rounding goes to the employee or investor.
Rounding a Number to n Decimal Places
If you were to use the Math.PI method to retreive the value pf pi, it might
return a number such as 3.141592653589793. This is a combersome string of digits to deal
with. You might want to round this value to 5 digits to the right of the decimal
point. The line below shows how to use the Math.round method to round pi to
5 digits to the right of the decimal point.
var n = Math.round(Math.PI * 100000) / 100000;
Of course, you can round other numbers besides pi to any number of digits to the
right of the decimal point. The number of zeros in the multiplier and divisor determines
the number of digits to the right of the decimal point. The example below rounds
the number 34.82765 to 2 digits to the right of the decimal point.
var m = 34.82765;
var n = Math.round(m * 100) / 100;
when you want to round a number a certain number of decimal places, choose the
apropriate Java Script Math object method (round, ceil, or floor) for
the situation.
|