• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint

## Rounding Floating-Point Numbers

NN 2, IE 3

### Problem

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

### 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.

### 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.

PREVIEW

Not a subscriber?

Start A Free Trial

• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint