Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Floats! (in PHP)

What's wrong with php floats?

$v = 5.2 * 3;

if($v==15.6) {
    echo 'Everything is fine =)';
} else {
    echo 'Okay something is wrong :S';
    var_dump($v); // float 15.6
}

Check this out too:

$v = 5.2 * 3;

if($v>15.6 AND $v<15.60000000001) {
    echo 'We are doomed :S';
    var_dump($v); // float 15.6
} else {
    echo 'Everything is fine =)';
}

I guess it has something to do with the internal representation or some obscure low level stuff? If that's the case, how do I get around this issue? Anything else I should know before using this to calculate real money transactions?

like image 833
HappyDeveloper Avatar asked May 19 '26 23:05

HappyDeveloper


2 Answers

I am sure this is a duplicate, so I'm making this a CW

$v = 5.2 * 3;
if (bccomp($v, 15.6) === 0) {
    echo 'Everything is fine =)';
} else {
    echo 'Okay something is wrong :S';
    var_dump($v); // float 15.6
}

will give 'Everything is fine =)'

like image 188
Gordon Avatar answered May 21 '26 12:05

Gordon


It has to do with the internal representation indeed :). Never compare float values. I think there will exists php classes/modules that work around this problem, but you can also store your money values as integers and multiply them by 100. Before display you can divide them again :)

like image 26
Lucas Moeskops Avatar answered May 21 '26 13:05

Lucas Moeskops



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!