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
276 views
in Technique[技术] by (71.8m points)

php - Why does `intval(19.9 * 100)` equal `1989`?

Boy, this one is really weird. I expect the following code to print 1990, but it prints 1989!

$val = '$19.9';

$val = preg_replace('/[^d.]/','',$val);
$val = intval($val * 100);

echo $val;

Why on earth is this happening?

Edit: and this code:

$val = '$19.9';
$val = preg_replace('/[^d.]/','',$val);
echo $val . "<br>";
$val = $val * 100;
echo $val . "<br>";
$val = intval($val);
echo $val;

Prints:

19.9
1990
1989

Why does intval(1990) equal 1989???

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is a precision issue inherent to floating point numbers in PHP, and lots of other languages. This bug report discusses it a bit, in the context of casting as an int:

http://bugs.php.net/bug.php?id=33731

Try round($val * 100) instead.


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

...