PHP Numbers
Rounding Floating-Point Numbers
Problem
You want to round a floating-point number, either to an integer value or to a set number of decimal places.Solution
To round a number to the closest integer, use round():$number = round(2.4);
printf("2.4 rounds to the float %s", $number);
This prints:
2.4 rounds to the float 2
To round up, use ceil():
$number = ceil(2.4);
printf("2.4 rounds up to the float %s", $number);
This prints:
2.4 rounds up to the float 3
To round down, use floor():
$number = floor(2.4);
printf("2.4 rounds down to the float %s", $number);
This prints:
2.4 rounds down to the float 2
Discussion
If a number falls exactly between two integers, PHP rounds away from 0:$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:
Rounding a positive number rounds up: 3
Rounding a negative number rounds down: -3
You may remember that 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 the
items in a user’s shopping cart:
$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";
This prints:
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:
$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:
$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.”
No comments:
Post a Comment