# 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.   Chapter 1. Strings  Chapter 2. Numbers and Dates  2.0 Introduction  2.1 Converting Between Numbers and Strings  2.2 Testing a Number's Validity  2.3 Testing Numeric Equality  2.4 Rounding Floating-Point Numbers  2.5 Formatting Numbers for Text Display  2.6 Converting Between Decimal and Hexadecimal Numbers  2.7 Generating Pseudorandom Numbers  2.8 Calculating Trigonometric Functions  2.9 Creating a Date Object  2.10 Calculating a Previous or Future Date  2.11 Calculating the Number of Days Between Two Dates  2.12 Validating a Date  Chapter 3. Arrays and Objects  Chapter 4. Variables, Functions, and Flow Control  Chapter 5. Browser Feature Detection  Chapter 6. Managing Browser Windows  Chapter 7. Managing Multiple Frames  Chapter 8. Dynamic Forms  Chapter 9. Managing Events  Chapter 10. Page Navigation Techniques  Chapter 11. Managing Style Sheets  Chapter 12. Visual Effects for Stationary Content  Chapter 13. Positioning HTML Elements  Chapter 14. Creating Dynamic Content  Chapter 15. Dynamic Content Applications  Appendix A. Keyboard Event Character Values  Appendix B. Keyboard Key Code Values  Appendix C. ECMAScript Reserved Keywords