Project cars | Mortgages | Mortgages | Car Finance | Mobile Phones
PHP not doing a simple subtraction?! [Archive] - ZGeek

PDA

View Full Version : PHP not doing a simple subtraction?!


simon_marklar
07-12-2005, 04:48 PM
$info['Total']=number_format(33690,0);
$Data1[$pubID]= number_format(35000,0);
$variance = $info['Total'] - $Data1[$pubID];

$variance= number_format($variance);
echo $variance


returns -2, when it should be -1310. WTF? what have i done wrong?

Spingo
07-12-2005, 04:59 PM
The number_format function returns a string.

Your third line of code is attempting to subtract a string from another string. Hence, the reason why you're getting -2 as the result.

Try this on for size:

$info['Total'] = 33690;
$Data1[$pubID] = 35000;
$variance = number_format($info['Total'] - $Data1[$pubID]);
echo $variance;


::edit:: This should explain in more detail:
After line 1, the value of $info['Total'] is a string equal to "33,690".
After line 2, the value of $Data1[$pubID] is a string equal to "35,000"

Strings can be used for mathematics. If there's a decimal place in the string, the string is considered to be a float. No decimal place and it's considered an integer.

The problem that you're getting is with the comma that is being inserted with the number_format function. PHP ignores everything after the comma. So when it comes to line three, the mathematical fucntion that it's performing is 33-35, which equals -2.

As a matter of good coding practice, you should perform string functions just before the string is to be displayed or treated as a string. Keep your values as integers or floats until that point.

simon_marklar
07-12-2005, 05:04 PM
crap. here i was thinking i was smart and reducing the number of number_format calls i had to make.

thanks heaps. +rep for you.

edit: yeah i understand whats happening. as soon as i read the word "string" i realised how stupid i had been. yesterday was my first day without caffiene after drinking 4+ red bulls a day for a few weeks, so i was a bit, um, not able to think straight :D not that that is an excuse for something so glaringly obvious...

cyberwired
12-12-2005, 09:02 PM
yus, spingo > *
*bows*