tags:

views:

88

answers:

3

I'm pulling my hair out here, so any help would be greatly appreciated. I need a php function that will take a float and round it down to the nearest half (x.0 or x.5). I found other functions that will round to the nearest fraction, but they round both ways.

The function I need can only round down.

Examples:

7.778 = 7.5

7.501 = 7.5

7.49 = 7.0

7.1 = 7.0

Thanks!

A: 

Floor won't help for fractions. I think you're looking for round() in PHP_ROUND_HALF_DOWN mode with the precision upped a bit?

http://www.php.net/manual/en/function.round.php

hollsk
No he's not - that makes 0.5 -> 0, instead of 1.
Dominic Rodger
Floor works if you change your decimal.. 4.51 * 10 = 45.1 - that floored is 45. Move your decimal back (45 / 10) and you're at 4.5
Dan Heberden
Yep - nicely solved above.
hollsk
If you execute `round(0.5, 1, PHP_ROUND_HALF_DOWN)`, you will get `0.5`. I verified it on PHP 5.3.
kiamlaluno
+10  A: 
$x = floor($x * 2) / 2;
Dominic Rodger
+1 This is pretty concise.
JYelton
+10  A: 

I'm assuming PHP has a floor function: floor($num * 2) / 2 ought to do it.

tzaman
+1 concise, just a tad behind in answer speed!
JYelton
+1, I don't care if you're not the fastest gun in the west by half a minute.
Josh K
@Josh Except this answer adds nothing... it's exactly the same as Dominic's.
Artefacto
@Artefacto: You could as well say that Dominic's answer adds nothing to this answer. This is not supposed to be a speed contest. I really hate it when people rush to upwote whatever answer happens to be the first one.
PauliL
@PauliL The question is: do you prefer to have two equal answers or only one? After you answer "only one", you'll see the only criterion to choose one that's less arbitrary is the moment it was posted -- whether it's 30 seconds or 30 minutes.
Artefacto
@PauliL Besides, whether you agree or not, this is sort of the community consensus; most high rep users will delete their answers if someone posted the same thing before them.
Artefacto
+1 from me. I could just have well have deleted my answer after seeing his - 30 seconds is fairly irrelevant.
Dominic Rodger