DekGenius.com
[ Team LiB ] Previous Section Next Section

2.4 Rounding Floating-Point Numbers

NN 2, IE 3

2.4.1 Problem

You want to round a floating-point value to the nearest whole number.

2.4.2 Solution

Use the Math.round( ) method on the value:

var roundedVal = Math.round(floatingPointValue);

The operation does not disturb the original value. Capture the rounded result in a variable.

2.4.3 Discussion

The algorithm that the Math.round( ) method uses is that any floating-point value that is greater than or equal to x.5 is rounded up to x+1; otherwise, the returned value is x.

JavaScript's Math object contains some other useful methods for trimming floating-point numbers of their fractional parts. Math.floor( ) and Math.ceil( ) return the next lowest and next highest integer values, respectively. For example, Math.floor(3.25) returns 3, while Math.ceil(3.25) returns 4. With negative values, the rules still apply, but the results seem backward at first glance: Math.floor(-3.25) returns the next lowest integer, -4; Math.ceil(-3.25) returns -3. For positive values, you can use the Math.floor( ) method as a substitute for what some other languages treat as the integer of a number.

Anytime a floating-point number evaluates to a number equal to an integer value, the decimal and digits to the right of the decimal go away. A variable can hold a floating-point number in one statement and be modified to an integer in the next. This drives some programmers crazy because they were indoctrinated by other languages to treat each type of number as a different data type.

2.4.4 See Also

Section 2.0.2 in the introduction of this chapter.

    [ Team LiB ] Previous Section Next Section