Reputation: 2676
I have a loop that calculates a couple revenue values then adds them together, like this:
$SalesGrowth = $C2012Sales+$C2011Sales;
In some cases, this works, and I get the expected, e.g.: 761.9 + 759.0 = 1520.9
In others, it looks like PHP randomly decides to round incorrectly (??) AND change the units (??) and I get:
8,788.0 + 8,794.3 = 16
What is going on here? I've even tried echoing out the separate sales values separated by a space, and they show up correctly, so the underlying figures aren't wrong.
Upvotes: 1
Views: 157
Reputation: 477268
Interpreted as a number, 8,788.0
is just 8
, and parsing stops at the comma.
You'll need some locale-aware number parsing if you want to allow gimmicks like thousands-separators.
Update: If you have the Zend Framework, you can do this:
require_once('Zend/Locale/Format.php');
$locale = new Zend_Locale('en_GB'); // #1
$v = "8,410.5";
$n = Zend_Locale_Format::getNumber($v, array('locale' => $locale,'precision' => 3));
echo 2 * $number; // prints "16821"
Instead of hard-coding the locale, you could try and take it from the environment: new Zend_Locale(setlocale(LC_ALL, ""))
Upvotes: 9
Reputation: 1761
Notice that 761.9 is a valid number, while 8,788.0 is not (from PHP's point of view).
So 8,788.0
in number context will evaluate as 8, just like 8,794.3
. And 8+8 = 16.
To fix this problem, process your data to make numbers formatted properly.
Upvotes: 2
Reputation: 11264
Dude the comma issue....
remove all the commas from the numbers before adding them...
str_replace(",","",$no1);
Upvotes: 3
Reputation: 137412
This is pretty simple... When you ask PHP to use the +
operator, it will implicitly convert these strings such as "8,788.0"
to an numeric value. Since you have a ,
character, it terminates the usefulness of the number, and it results in it being interpreted as 8
. And so on...
Get rid of the non [0-9.]
characters and it will work better.
Upvotes: 2