Page 1 of 1

Problems with floats dropping £1000

Posted: Fri Oct 29, 2010 4:57 am
by phil_poole
Hi, I'm new to php and am usually a violinist! I have written a shopping cart for a friends site, and populate $_SESSION with the $total_price. It works fine most of the time, but when an order was placed for £1,094.16, and the script added the postage (£31.37), the £1,094.16 was devalued to £1.00 (luckily it's not live yet!!!).

The price is displayed fine before postage is added, suggesting it is stored corectly in the $_SESSION variable. It goes adrift in the calculation:

$grand_total = (number_format(($_SESSION['total-price']), 2)) + (number_format($post_cost, 2));
$grand_total = number_format($grand_total, 2);

Any help with this would be appreciated. As the language is dynamically typed, I'm assuming it's not a casting issue.

Cheers,

Phil

Re: Problems with floats dropping £1000

Posted: Fri Oct 29, 2010 6:21 am
by Weirdan
You need to make sure you operate with numbers and not storing strings like '200£' in session. To start with, you should first sum, and format afterwards:

Code: Select all

$grand_total = (number_format(($_SESSION['total-price']), 2)) + (number_format($post_cost, 2)); // <== WRONG
$grand_total = number_format($_SESSION['total-price'] + $post_cost, 2); // <=== RIGHT

Re: Problems with floats dropping £1000

Posted: Sun Oct 31, 2010 5:42 am
by phil_poole
Thank you very much. I had realised the formatted comma must have something to do with it while running last night. Hadn't dawned on me that I was dealing with strings though.

Ah well, you can't beat a quality schoolboy error. :oops: