php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50398 convert float to int causes an error
Submitted: 2009-12-07 12:40 UTC Modified: 2009-12-07 12:48 UTC
From: blanca at netvision dot net dot il Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 5.3.1 OS: windows xp
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: blanca at netvision dot net dot il
New email:
PHP Version: OS:

 

 [2009-12-07 12:40 UTC] blanca at netvision dot net dot il
Description:
------------
when converting 12.999999999999999 from float to int,
the output is 12

but, when converting 12.9999999999999999 from float to int,
the output is 13 

Reproduce code:
---------------
$a=12.9999999999999999;
$b=(int)$a;
$a=12.999999999999999;
$c=(int)$a;
$str="\$b is: ".$b." and \$c is: ".$c;
echo $str;

Expected result:
----------------
$b is: 12 and $c is: 12

Actual result:
--------------
$b is: 13 and $c is: 12

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-12-07 12:48 UTC] johannes@php.net
Floating point values have a limited precision. Hence a value might 
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly 
printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE
754 is, read this:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.

The docs say

"When converting from float to integer, the number will be rounded towards zero."

http://php.net/manual/en/language.types.integer.php#language.types.integer.casting

Now combining this with the unprecise nature of floating point numbers this gives "random" results.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 16 20:01:32 2025 UTC