tags:

views:

172

answers:

1
+1  Q: 

PHP round decimals

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.

+4  A: 
function round_to_nearest_half($number) {
    return round($number * 2) / 2;
}
Artefacto
What is the $f? And you don't need the precision if it is 0.
plor
function round_to_nearest_half($original){return (round($original * 2) / 2);}Would be more like it !
RobertPitt
@plor yeah, I changed my mind about the variable name half-way. ANd yes, you're right, you don't need the second argument, I just picked the syntax the OP used.
Artefacto
@Artefacto I knew what you were saying, and I probably should have asked "What the $f?".
plor
If you change it to `function round_to_nearest_half($number)` or `return round($f * 2, 0) / 2;` it might actually work :p.
wimvds
@Artefacto - thanks...this function works fine.
Sergio