Firstly, Check the two digits sequence next to the decimal place value. If xy mod(25) > 12 then round up and the nearest quarter is xy + (25 – xy mod(25)). On rounding up if you get the nearest quarter ending in . 00 then increase the one's place value by 1.
We round 0.5 to the nearest even digit. Example: 7.5 rounds up to 8 (because 8 is an even number) but 6.5 rounds down to 6 (because 6 is an even number)
Since you're looking for fourths (.00
, .25
, .50
, .75
), multiply your number by 4, round to nearest whole number as desired (floor
if down, ceil
if up), then divide by 4.
1.32, down to nearest fourth:
1.32 * 4 = 5.28
floor(5.28) = 5.00
5.00 / 4 = 1.25
Same principle applies for any other fractions, such as thirds or eighths (.0
, .125
, .25
, .375
, .5
, .625
, .75
, .875
). For example:
1.77, up to nearest eighth:
1.77 * 8 = 14.16
ceil(14.16) = 15.00
15.00 / 8 = 1.875
Just for fun, you could write a function like this:
function floorToFraction($number, $denominator = 1)
{
$x = $number * $denominator;
$x = floor($x);
$x = $x / $denominator;
return $x;
}
echo floorToFraction(1.82); // 1
echo floorToFraction(1.82, 2); // 1.5
echo floorToFraction(1.82, 3); // 1.6666666666667
echo floorToFraction(1.82, 4); // 1.75
echo floorToFraction(1.82, 9); // 1.7777777777778
echo floorToFraction(1.82, 25); // 1.8
Please note that the answer isn't really water tight. Since we're dealing with floats here it's not guaranteed that when you divide the rounded number by the denominator it returns a neatly round number. It may return 1.499999999999 instead of 1.5. It's the nature of floating point numbers.
Another round is needed before returning the number from the function.
Just in case someone lands here from google like I did :)
Look at example #3 on here and it is half of your solution - http://php.net/manual/en/function.round.php
According to the mround()
function in Excel:
function MRound($num,$parts) {
$res = $num * $parts;
$res = round($res);
return $res /$parts;
}
echo MRound(-1.38,4);//gives -1.5
echo MRound(-1.37,4);//gives -1.25
echo MRound(1.38,4);//gives 1.5
echo MRound(1.37,4);//gives 1.25
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