**You want to round a floating-point number**, either to an integer value or to a set number of decimal places.

To round a number to the closest integer, **use round()**:

1 2 |
$number = round(2.4); printf("2.4 rounds to the float %s", $number); |

This prints:

1 |
2.4 rounds to the float 2 |

To round up, **use ceil()**:

1 2 |
$number = ceil(2.4); printf("2.4 rounds up to the float %s", $number); |

This prints:

1 |
2.4 rounds up to the float 3 |

To round down, **use floor()**:

1 2 |
$number = floor(2.4); printf("2.4 rounds down to the float %s", $number); |

This prints:

1 |
2.4 rounds down to the float 2 |

If a number falls exactly between two integers, **PHP rounds away from 0**:

1 2 3 4 5 |
$number = round(2.5); printf("Rounding a positive number rounds up: %s\n", $number); $number = round(-2.5); printf("Rounding a negative number rounds down: %s\n", $number); |

This prints:

1 2 |
Rounding a positive number rounds up: 3 Rounding a negative number rounds down: -3 |

Floating-point numbers don’t always work out to exact values because of how the computer stores them.

This can create confusion. A value you expect to have a decimal part of “0.5” might instead be “.499999…9” (with a

whole bunch of 9s) or “.500000…1” (with many 0s and a trailing 1).

PHP automatically incorporates a little “**fuzz factor**” into its rounding calculations, so you don’t need to worry about this.

To keep a set number of digits after the decimal point, **round()** accepts an optional precision argument.

For example, perhaps you are calculating the total price for theitems in a user’s shopping cart:

1 2 3 4 5 6 7 |
$cart = 54.23; $tax = $cart * .05; $total = $cart + $tax; $final = round($total, 2); print "Tax calculation uses all the digits it needs: $total, but "; print "round() trims it to two decimal places: $final"; |

1 2 |
Tax calculation uses all the digits it needs: 56.9415, but round() trims it to two decimal places: 56.94 |

To round a number down, use the **floor()** function:

1 2 3 4 |
$number1 = floor(2.1); // floor(2.1) is the float 2.0 $number2 = floor(2.9); // floor(2.9) is the float 2.0, also $number3 = floor(-2.1); // floor(-2.1) is the float -3.0 $number4 = floor(-2.9); // floor(-2.9) is the float 3.0, also |

To round up, use the **ceil()** function:

1 2 3 4 |
$number1 = ceil(2.1); // ceil(2.1) is the float 3.0 $number2 = ceil(2.9); // ceil(2.9) is the float 3.0, also $number3 = ceil(-2.1); // ceil(-2.1) is the float -2.0 $number4 = ceil(-2.9); // ceil(-2.9) is the float 2.0, also |

These two functions are named because when you’re rounding down, you’re rounding “**toward the floor**,” and when you’re rounding up, you’re rounding “**toward the ceiling**.”

For information on comparing floating-point numbers; documentation on **ceil()**, on **floor()**, on **round()**, and on printf formatting strings such as %s.