#49871 [Bgs]: unexpected result converting float to int
ID: 49871
User updated by: daniel dot buschke at nextiraone dot de
Reported By: daniel dot buschke at nextiraone dot de
Status: Bogus
Bug Type: Math related
Operating System: Linux
PHP Version: 5.2.11
New Comment:
(int)(string)$b
that does the job but is ugly, too
Previous Comments:
------------------------------------------------------------------------
[2009-10-14 11:16:23] sjoerd@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.
------------------------------------------------------------------------
[2009-10-14 08:36:03] daniel dot buschke at nextiraone dot de
Description:
------------
Hi,
when I convert following float:
float(232)
into an int I get:
int(231).
The float was calculated by 2.32 * 100. I know that this may result in
232.00000000001 or 231.999999999 but the behavior is unexcpected because
var_dump does not show the real (more or less wrong) float number.
This one is exact the same as #2835 but the bug was closed without any
further comments. The provided solution is unacceptable.
How to convert 2.32 into an integer of the value 232?
BTW: Please do not set this bug to bogus or closed with the default
text for that problem ;-). As you can see in your bugtracker the
community wants a solution for that. Please also remember that PHP is a
scripting language which mainly ignores datatypes. This problem is not
comprehensible to beginners (webdesigners ;-) ).
I do not want to blame you with that but I just want to find a usefull
solution. Please keep communication with community.
regards
Daniel
Reproduce code:
---------------
<?php
messUpFloat(2.32);
messUpFloat(8.28);
function messUpFloat($float) {
echo '--------- ' . $float . ' --------' . PHP_EOL;
$a = $float;
var_dump($a);
$b = $a * 100 + 0;
var_dump($b);
$c = (int)$b;
var_dump($c);
}
?>
Expected result:
----------------
--------- 2.32 --------
float(2.32)
float(232)
int(232)
--------- 8.28 --------
float(8.28)
float(828)
int(828)
or (but not preferred ;-) )
--------- 2.32 --------
float(2.32)
float(231.999999999999999)
int(231)
--------- 8.28 --------
float(8.28)
float(827.999999999999999)
int(827)
Actual result:
--------------
--------- 2.32 --------
float(2.32)
float(232)
int(231)
--------- 8.28 --------
float(8.28)
float(828)
int(827)
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=49871&edit=1
Thread (4 messages)