dmn
dmn

Reputation: 985

PHP Ignoring Digits to the Right of the Decimal Point in Equation

I have a variable $x whose value is read in from an XML file. The value being read from the XML is 1.963788, nothing more, nothing less. When I output $x, I see that the value in $x is in fact 1.963788. All is right with the world.

But then when I use x in an equation such as

$pl = $x*125.0-200.0;

The value of $pl ends up being -75. For whatever reason, PHP seems to be ignoring, or just getting rid of, the digits to the right of the decimal point in $x, which makes $x contain 1. I thought maybe there was a snowball's chance in hell that this occurred in other languages too, so I wrote it up in C++ and, big surprise, I get the right answer of 45.4735.

Anyone ever encountered this before or know what's going on? Thanks.

Upvotes: 1

Views: 660

Answers (4)

Crashspeeder
Crashspeeder

Reputation: 4311

Your number appears to have failed casting as a float. If I use '1,963788' I get your result. If I use '2,963788' I receive a result of 50. According to the PHP docs for intval (and that's what it appears PHP is trying to cast this as, an integer): Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Check the value $x actually has carefully. It may not be what you expect since PHP seems to disagree that it is, in fact, a float or it would have typed it as such.

Upvotes: 1

rubayeet
rubayeet

Reputation: 9400

Just before you compute $pl, do a var_dump on $x to see what is the actual value stored in it. I've tried your code and it is returning the correct value 45.4735, so I might not be PHP's fault.

Upvotes: 0

skulled
skulled

Reputation: 143

It probably is due to the fact that $x is being interpreted as a string, and converted to an integer and not a float value.

Try:

$pl = (float) $x * 125.0 - 200.0;

Upvotes: 1

Daniel
Daniel

Reputation: 1527

Have you tried using floatval? Maybe PHP interprets your number as a string and the standard conversion just casts it to integer.

Upvotes: 1

Related Questions