Page 1 of 1

[SOLVED] PHP basic math question

Posted: Mon Mar 31, 2014 7:17 am
by Andaho
I have edited my tpl files to display this:

RRP: £100.00 You Save: £0
Price: £90.00

I'm trying to get it to display how much is saved... I used this line:

Code: Select all

<span class="price-rrp">&nbsp;You Save: £<?php echo $price - $special; ?></span>
Why is it not working? :(

Re: PHP basic math question

Posted: Mon Mar 31, 2014 11:36 am
by rph
Because the prices have the pound symbol in them. This is one of the areas in PHP where things can get tricky fast. Something like "£100.00" is a non-numeric string. That means PHP can't turn it into a number when doing math. But instead of throwing an error PHP silently converts the string to 0 and continues.

One solution is to strip all the non-numeric characters then do the math:

Code: Select all

<?php echo preg_replace('/[^0-9\.]/', '', $price) - preg_replace('/[^0-9\.]/', '', $special); ?>
This is a very "hacky" way to do the code. I'd recommend not using it if possible.

A better solution is doing the math in the controller file using the non-formatted prices then send the output to the template.

Re: PHP basic math question

Posted: Mon Mar 31, 2014 12:05 pm
by Cue4cheap
Maybe see http://www.opencart.com/index.php?route ... _license=0

Might make less work for you.
Mike

Re: PHP basic math question

Posted: Mon Mar 31, 2014 7:26 pm
by Andaho
Thanks guys, I don't know why I tried to do this myself without searching for a free extension for it first!

I'm going to try out this one: http://www.opencart.com/index.php?route ... on_id=8319

Re: [SOLVED] PHP basic math question

Posted: Mon Mar 31, 2014 7:49 pm
by Andaho
I had already started butchering my php code, so I used code from that extension to add the following lines in the copied locations:

Code: Select all

$this->data['yousave'] = $this->currency->format($this->tax->calculate($product_info['price']-$product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')));
$this->data['yousavepercent'] = round(($product_info['price']-$product_info['special'])*100/$product_info['price'],0);

$yousave = $this->currency->format($this->tax->calculate($result['price']-$result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
$yousavepercent = round(($result['price']-$result['special'])*100/$result['price'],0);
Way too complicated for me to even start understanding! - but now in my product.tpl file, when I refer to $yousave I get what I want :D - and I have the bonus of having % too :)