php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #40280 Type casting from float into string
Submitted: 2007-01-29 22:32 UTC Modified: 2007-01-30 07:13 UTC
From: my-design at gmx dot net Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: Irrelevant OS: Slackware 11; Kernel 2.6.15.6
Private report: No CVE-ID: None
 [2007-01-29 22:32 UTC] my-design at gmx dot net
Description:
------------
Casting from float into string rounds the number without a notice.

There seems to be some difference between rounding precision for an string casting and internal float storage precision; that is perhaps not a bug in float handling itself, but is totally unexpected and is a great error source for some scripts.

In the above example the value for $x was originally integer 19, stored into the database as float and restored later as given. There is no method to see the difference directly, only in serialised data.

Tested PHP versions: 4.4.4 , 4.3.11

Reproduce code:
---------------
$x=18.99999999999999289457264239899814128875732421875;
print "x=${x}\n";
$a=array();
$a[$x]=$x;
print_r($a);



Expected result:
----------------
x=18.999999999999
Array
(
    [18] => 18.999999999999
)


Actual result:
--------------
x=19
Array
(
    [18] => 19
)



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-01-30 07:13 UTC] bjori@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.


 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Sun Jun 14 12:00:01 2026 UTC