Is it possible to round a decimals to the nearest .5 with PHP like this:
number | round
----------------
1.29 | 1.50
2.03 | 2.00
1.43 | 1.50
1.13 | 1.00
11.38 | 11.50
I tried with:
$rnd= round($number,2);
but I get decimals like the one in the column "number" above.
Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>
The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.
There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.
So, ceil( $the_number / 5 ) * 5 is the final answer. Or round( $the_number / 5 ) * 5 if you want to round to the nearest 5.
function round_to_nearest_half($number) {
return round($number * 2) / 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With