Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

floating point - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 =)'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...