johnlemon
johnlemon

Reputation: 21449

Php and floating numbers

I have this example

$x = 0.154 + 0.408;
$y = 0.562;
echo $x - $y;

You would think it's 0 but it's not ( well maybe it depends on your system and php version ). Anyway for those who don't see 0, what's the correct way to do float operations ?

Upvotes: 0

Views: 161

Answers (3)

martinstoeckli
martinstoeckli

Reputation: 24071

You really should understand the problem (there is no library which can magically solve this problem, PHP is all you need).

A very good article you can find here, it's actually written for Delphi, but the problem is not specific to any language: Comparing floating point values

Please also read the warning in the documenation of PHP: Floating point precision

Upvotes: 0

Oyeme
Oyeme

Reputation: 11225

$x = bcadd (0.154 ,0.408);
$y = 0.562;
echo bcsub($x,$y);

Upvotes: 2

Crozin
Crozin

Reputation: 44376

It's actually not related to the PHP itself, that's how computers work - some numbers cannot be reprezented precisely so you have to keep in mind that when you work with floats and doubles you work on numbers approximations.

You can read more about floating point on Google: floating point arithmetic

Upvotes: 0

Related Questions