Problems with floats dropping £1000

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phil_poole
Forum Newbie
Posts: 2
Joined: Fri Oct 29, 2010 4:49 am

Problems with floats dropping £1000

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Problems with floats dropping £1000

Post 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
phil_poole
Forum Newbie
Posts: 2
Joined: Fri Oct 29, 2010 4:49 am

Re: Problems with floats dropping £1000

Post 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:
Post Reply