0

I'm trying to modify a pseudo-shopping cart (it's array based storing values in user meta and not database) PHP file that wrongly displays currency > 1000 as 0.01

Here's the block I want to change:

public function get_cart_value()
{
    $cart = $this->cart;
    $prices = array();

    $cart = apply_filters('ss_mod_cart_value', $cart);

    foreach ($cart['products'] as $product)
    {
        array_push( $prices, array('price'=>trim($product['price']), 'discount' => trim($product['discount'] )));            
    }

    $total = 0;

    foreach($prices as $price)
    {
        $price = $this->calc_discount($price['price'], $price['discount']);    
        $price = str_replace('.', '',  $price['final_price']);
        $total += $price;
    }


    $total = number_format($total/100, 2);

    return $total;
}

The cart button it works on will correctly display the total values of items less than 4 digits, for example:

300 + 500 = 800 

but

300 + 500 + 1000 = 800.01 instead of 1,800

I've been trying to change number_format() to make it work but cannot find a solution.

Marty
  • 39,033
  • 19
  • 93
  • 162
hanasuz
  • 3
  • 1
  • Perhaps a bit ghetto, but have you tried something like `(10*100)`? – Helpful Apr 10 '14 at 05:49
  • 1
    Your whole `foreach` loop looks suspect. You're overwriting the value of `$price` and then using that result for the next calculation, but the bit that baffles me is replacing the decimal point. This should be basic arithmetic but it looks like you're doing some odd string conversions along the way that are corrupting your result. –  Apr 10 '14 at 05:49
  • try http://stackoverflow.com/questions/5139793/php-unformat-money this solution – Kasun Rajapaksha Apr 10 '14 at 06:19

1 Answers1

0

I think by this line

$price = str_replace('.', '',  $price['final_price']);

300+500+ "1000";

your numbers like 1,000 are converted to a string and then your total becomes 801.

you have to convert to float in proper way as suggested in this

PHP: unformat money

Community
  • 1
  • 1
Kasun Rajapaksha
  • 536
  • 1
  • 5
  • 22
  • I followed the thread and found a workaround: replace str_replace with floatval as in $price = floatval(preg_replace('/[^\d\.]/', '' , $price['final_price'])); and changed total to $total = number_format($total, 2); Now the currency is displaying correctly. Thank you very much! – hanasuz Apr 10 '14 at 07:12