Home » Php » rounding – PHP round decimals

rounding – PHP round decimals

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:
function round_to_nearest_half($number) {
    return round($number * 2) / 2;
}

Answer:

You don’t want write any function for this php round function already have the option, in mode is a third argument of round function. for more reference PHP Round Function