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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

<?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
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.