Forum Moderators: coopster
I've got a project that requires a currency display that acts like this:
$1.01 (through $1.49) would be rounded to $1.50
and
$1.51 (through $1.99) would be rounded to $2.00
The second one is easy with ciel(), but I'm wondering if there's already a built-in function that convert .01 to .49 to .50 ... or will I have to write my own function to detect these float values and round accordingly?
Neophyte
round() works in the way one would expect it to, but the specification I'm working to is out of the ordinary.
For example:
if you use the round() function with 2 places of precision - i.e. round(f, 2) - on a number like this: 1.0347682119205, you would get the expected 1.03.
However, my specification calls for rounding any remainders UP to the NEXT .5. Accordingly, I need 1.0347682119205 to be displayed like so: 1.50. If the number were 1.5347682119205, I need the result to be like this: 2.00.
That's what I need to happen.
I've looked at the different rounding functions in the PHP manual, and it looks like I might have to write my own function to evaluate the remainder and tack on a ".50" or ".00" as appropriate, but just wanted to know if anyone else has had the need to do this and has found an off the shelf solution.
Neophyte
Just decided to do it my self. Here's the result for anyone else who might be interested:
<?php
// Round a number's REMAINDER to the next .50.
function roundFifty($num)
{
if(is_float($num))
{
$x = explode('.', round($num, 2), 2);
$x = $x[1] <= '50' ? $x[0] . '.50' : $x[0] + 1 . '.00';
return $x;
}
else
{
return $num . '.00';
}
}
$n = 1.5347682119205;
echo roundFifty($n);
?>
Neophyte
function ceil_half($num)
/** Like ceil(), but in increments of 0.5 rather than 1.0. */
{ return ceil($num*2)/2; } ceil_fraction($num, $fraction)
/** Like ceil(), but in increments of $fraction rather than 1.0. */
{ return ceil($num/$fraction)*$fraction; }? map ceil_fraction(_, 1/2), [0.99, 1.00, 1.01, 1.24, 1.25, 1.49, 1.50, 1.51] =>
[1.00, 1.00, 1.50, 1.50, 1.50, 1.50, 1.50, 2.00]
map ceil_fraction(_, 1/4), [0.99, 1.00, 1.01, 1.24, 1.25, 1.49, 1.50, 1.51] =>
[1.00, 1.00, 1.25, 1.25, 1.25, 1.50, 1.50, 1.75]