HiveBrain v1.2.0
Get Started
← Back to all entries
debugphpMinor

Rounding prices

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pricesroundingstackoverflow

Problem

I have written a PHP function that should round prices to a desired format.

E.G. 1547.86456

That should be : 1547.85

OR

if desired : 1547.86

The code has been written and it works under several conditions. BUT I wonder if I have overlooked something. AND maybe I have used solutions that could be much easier and less CPU intensive.

Hence therefore I would like to ask if anyone could see ANY errors or optional simplifications.

 0){
        $props  = explode('.', $return);
        $ext    = 0;

        if(isset($props[1]) === true){
            $props[1] = round($props[1] / $nearest) * $nearest;

            if($props[1] > 100){
                $ext        = floatval(substr_replace($props[1], '.', 1, 0));

                $props[1]   = 0;
            }
            else{
                $ext        = 0;
            }
        }

        $number = str_replace(',', '', number_format($props[0].'.'.$props[1] + $ext, $BehindComma));
    }
    else{
        $number = str_replace(',', '', number_format($num, $BehindComma));
    }

    return($number);
}

$value = 1547.86456;

echo RoundPrice($value, 10);
?>

Solution

Consider using the Money pattern which uses integer instead of float values. Otherwise you might be losing 'pennies' because of rounding errors.

A PHP implementation of the Money pattern is found here: https://github.com/mathiasverraes/money

Context

StackExchange Code Review Q#87565, answer score: 4

Revisions (0)

No revisions yet.