2

This is killing me! I've never had so much trouble and I can't figure out what I'm doing wrong here.

If I have a number, say 2.32, and I want to do math with it it won't work out. The very simplest example:

$income = $commission; //Commission is 2.32, retrieved from XML echo "income: $income<br>"; $income100 = $income*100; echo "income100: $income100<br>"; 

The result I get is:

income: 2.32 income100: 200 

How can I use a decimal number accurately with math without it changing it?

Thanks so much!

4
  • $income = (float) $commission; Likely a simpleXML object Commented Oct 29, 2012 at 20:04
  • @bigman how should then $income*100 work ? Commented Oct 29, 2012 at 20:05
  • @bigman: Why would you cast it as a string so that it hopefully converts to float... just cast it as a float Commented Oct 29, 2012 at 20:05
  • 2
    Wow, I didn't realize I made it a string, meant to throw a float. Brain fart Commented Oct 29, 2012 at 20:06

4 Answers 4

5

You need to assign $income in the following manner to get rid of the underlying SimpleXMLElement:

$income = (float) $commission; 

Example of what happens when you don't:

$x = simplexml_load_string("<a>2.4</a>"); echo $x * 100; // output: 200 
Sign up to request clarification or add additional context in comments.

Comments

2

Besides using floats as Tim said, also make sure to use the BC Math functions when performing arithmetic operation on floating point numbers. Specifically bcmul():

$income100 = bcmul($income, 100);

Comments

0

The problem with floating-point numbers is that you cannot represent decimal numbers with them (unless it can be written as a/b for integer a and b, and even then only if abs(a) < pow(2,52) and b is a power of 2).

You may be better off using string functions to get an integer value:

$tmp = explode(".",$commission); $tmp = intval($tmp[0].str_pad(substr($tmp[1],0,2),2,"0")); 

This will split up the integer part from the decimal part, ensure the decima part is two digits long, and shove it on the end of the integer part, thus effectively multiplying the original number by 100.

1 Comment

No, but I wasn't trying to. There's obviously something going wrong in the conversion to a number that's resulting in the decimal being dropped, but this answer solves that problem.
0

I think the easiest solution would be to cast it to a float with floatval()

$income = floatval($comission)

leave the rest of the code as is and it should work as intended.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.