0

I have a string "65.57". I need get the int 6557

However...

(int) (((float) "65.57") * 100) === 6556

Strangely, when broken up, everything works as expected:

((float) "65.57") * 100) === 6557.0

and

(int) 6557.0 === 6557

but when inlined, I'm getting 6556.

Ben
  • 2,962
  • 2
  • 20
  • 26
  • `echo serialize((float) "65.57" * 100);` cast it to an int and it just truncates. You could round, but still shouldn't use float here. – AbraCadaver Apr 05 '17 at 18:23
  • The answer to why this happens is in the second paragraph of the "Warning Floating point precision" topic on [this page](http://php.net/manual/en/language.types.float.php#warn.float-precision) – DFriend Apr 05 '17 at 18:35
  • ["Never cast an unknown fraction to integer"](http://us2.php.net/manual/en/language.types.integer.php#language.types.integer.casting) String manipulation feels like an overkill (for me). You could use `round` instead. – csirmazbendeguz Apr 05 '17 at 18:54

3 Answers3

1

Don't mess with floats, they will only bring you pain. :)

I'd just strip out the dot:

$s = '65.57';
$x = str_replace('.', '', $s);

If you actually need an int, then cast the result:

$x = (int) str_replace('.', '', $s);
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • Yeah, I was thinking of going down that route. Just seemed really strange that when inlined, I got one result and when broken up into separate statements I got the expected result... – Ben Apr 05 '17 at 18:19
0

Like Alex said

Don't mess with floats, they will only bring you pain. :)

function parsePrice($str) {
    $parts = explode('.', $str);
    return intval($parts[0]) * 100 + intval($parts[1]);
}

var_dump(parsePrice('65.57'));

// Output: int(6557)
Sammitch
  • 30,782
  • 7
  • 50
  • 77
0

You have stumbled upon a floating point inaccuracy problem.

The problem is that floating points always has a number of decimals, and sometimes a number of decimals hidden from you, because of this, you will once in a while end up with them not always multiplying together as you would expect.

The real reason lies in binary, we are used to a 10-base numeric system. in the same way as we cannot perfectly describe 1/3 (~0.3333333333..) binary cannot always describe our "perfectly fine decimal numbers" in 10-base, you can adjust the precision PHP uses to calculate floats with in your php.ini. But you would be far better of with avoiding floats, and make your calculations using integers.

More on the topic:

Floating point inaccuracy examples

Can I rely on PHP php.ini precision workaround for floating point issue

Community
  • 1
  • 1
Iesus Sonesson
  • 854
  • 6
  • 12