0

I have the following code to round Magento products to to nearest $x.90, $x.80, $x.85, etc. but the input is by hand. What I need is a new function to bring the price to the nearest 10 cents by just pushing a button. So if the price is $11,87 I need it to be $11,90, if the price is $11,63 I need it to be $11,60.

How do I do this?

protected function _round($price, $roundTo = 0.00, $type = 'normal')
{
    $roundTo = ltrim(number_format($roundTo, 2, '.', ''), '0');

    if ($type === 'normal') {
        return round($price);
    }

    $safety = 99999999;

    if ($type === 'up' || ($type === 'down' && $roundTo < $price)) {
        while(substr($price, -(strlen($roundTo))) != $roundTo) {

            if ($type === 'up') {
                $price += .01;
            }
            else {
                $price -= .01;
            }

            $price = number_format($price, 2, '.', '');

            if (--$safety < 1) {
                throw new Exception('Error');
            }
        }

        return $price;
    }

    return false;
}   
  • 3
    In php, `round($value, 1)` – fedorqui Feb 15 '13 at 09:29
  • Guess you are Canadian – Ed Heal Feb 15 '13 at 09:29
  • 2
    Please **never-ever** use [IEEE Double](http://en.wikipedia.org/wiki/Double-precision_floating-point_format) types for money! The fractions wont add up as you expect in some cases! See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – complex857 Feb 15 '13 at 09:31
  • @EdHeal European. You goddamn racist. :-) –  Feb 15 '13 at 09:32
  • @complex857 I bought this script and it works fine for Magento so. –  Feb 15 '13 at 09:33
  • @hidde - I am not a racist. The Canadians have just given up distributing one cent coins - http://www.bbc.co.uk/news/world-us-canada-21328892 - and the government recommends to round to 5 cents – Ed Heal Feb 15 '13 at 09:35
  • Well, it looks pretty suspicious to me with this `$safety` for preventing it to run forever when `$roundTo` cannot be reached because fractions are not addig up *exactly* (or maybee the input is too far from the desired value) (-: – complex857 Feb 15 '13 at 09:36
  • @EdHeal I was kidding. The reason is that the products are imported automatically but the prices in the file ain't 'user friendly'. This is a quick fix to create user friendly prices. –  Feb 15 '13 at 09:39

1 Answers1

2

This little function would work.

function roundPrice($price){
    $rounded = round($price, 1);
    return number_format($rounded, 2);
}

$newprice = roundPrice($InputYourValueHere);

// Output the value for the purposes of the example
echo $newprice;
Rob
  • 738
  • 3
  • 10
  • 23
  • Sort of, remember the `return` value needs assigning to something. In the above example the `return` value is stored in the `$newprice` variable. – Rob Feb 15 '13 at 10:26