|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46537 Incorrect addition of float and string
Submitted: 2008-11-10 18:43 UTC Modified: 2008-11-10 20:13 UTC
From: syphon dot and dot the dot trick at gmai dot com Assigned:
Status: Not a bug Package: Strings related
PHP Version: 5.2.6 OS: *
Private report: No CVE-ID: None
 [2008-11-10 18:43 UTC] syphon dot and dot the dot trick at gmai dot com
I've been setting up our system to receive payments via Paypal. Paypal talks via IPN to a URL that I specify. In my code I have logic to verify the transaction. 

On one line I ran into the problem of addition when verifying transaction amounts.

I have tried this test on Win32 running PHP 5.2.3 (Basic AppServ install) and on our live linux environment PHP 5.2.6 with both showing the same results.

Reproduce code:
$SubTotal = "67.43";
$Tax = "3.37";

$Amount = $SubTotal + $Tax;

$Array = array("mc_gross" => "70.80");

echo ($Amount == $Array['mc_gross']) ? $Array['mc_gross'].' is equal to '.$Amount : 'These values are not equal. '.$Array['mc_gross']." is not equal to ".$Amount;

echo '<br /><br />Second Test<br /><br />';
$Amount = 70.8;

echo ($Amount == $Array['mc_gross']) ? $Array['mc_gross'].' is equal to '.$Amount : 'These values are not equal. '.$Array['mc_gross']." is not equal to ".$Amount;

Expected result:
The variable mc_gross, a string with a string value "70.80" should equal the variable $Amount with the float value of 70.8

Actual result:
The first test adds the two variables ($Subtotal and $Tax) together into the variable $Amount. Using var_dump php tells us that $Amount is a float with the value 70.8

When comparing that variable to the one supplied by Paypal (mc_gross) php says that the values are not equal to each other.

If you redeclare the variable $Amount and with the value 70.8 and try again, php says the values are equal. 

var_dump confirms the variable types and value.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2008-11-10 20:13 UTC]
Floating point values have a limited precision. Hence a value might 
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly 
printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE
754 is, read this:
Thank you for your interest in PHP.

PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Mon Dec 11 06:01:30 2023 UTC