Ben
Ben

Reputation: 3060

Odd casting behavior

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.

Upvotes: 0

Views: 39

Answers (3)

Iesus Sonesson
Iesus Sonesson

Reputation: 854

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

Upvotes: 0

Sammitch
Sammitch

Reputation: 32232

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)

Upvotes: 0

Alex Howansky
Alex Howansky

Reputation: 53543

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);

Upvotes: 1

Related Questions