Jump to content

[SOLVED] Is it possible to sort of round decimals? i.e. *.527 -> *.5 or *.245 -> *.25


darp

Recommended Posts

While filling out a form I want the data to be stored in both metric and standard. The figures for the standard entries need only be accurate to the nearest quarter ounce. So the user input is grams and that figure is automatically divided by 28.349523125 to get the equivalent ounces. The problem is, entries like 100 grams are converted to  3.52739619496 ounces. What I would really like to see is 3.5 ounces and 92 grams converted to 3.25 ounces instead of 3.24520449936. The only values that I want to see are *.00 || *.25 || *.50 || *.75

 

Is this possible?

 

P.S. The reason the original entry has to be in grams is because most of the original data is provided that way so doing the conversion the other way is not really an option.

 

The only way I can think of is doing it manually like this:

 

function round_to_quarter($num) {
    $floor = floor($num);
    $fractional_part = $num - $floor;

    if ($fractional_part < 0.125) {
        return $floor;
    }

    if ($fractional_part < 0.375) {
        return $floor + 0.25;
    }

    if ($fractional_part < 0.625) {
        return $floor + 0.5;
    }

    if ($fractional_part < 0.875) {
        return $floor + 0.75;
    }

    return $floor + 1;
}

 

It's not very pretty, but I can't think of another way.

<?php
function roundQuarter($num) {
return round($num * 4) / 4;
}

echo roundQuarter(25.99); // 26
echo roundQuarter(24.3); // 24.25
// etc...
?>

 

To explain... to round to decimal x, multiple the number by (1/x) - in this case, 1/.25 results in 4, round normally, and then divide it by 1/x again. A more general formula would be:

 

<?php
function roundDecimal($num, $decimal) {
$tmp = 1 / $decimal;
return round($num * ($tmp)) / $tmp;
}

echo roundDecimal(25.34, 0.1); // rounds to the nearest tenth
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.