Edit report at https://bugs.php.net/bug.php?id=62465&edit=1
ID: 62465
User updated by: fabrizio at queensboro dot com
Reported by: fabrizio at queensboro dot com
Summary: intval of floats
Status: Not a bug
Type: Bug
Package: *General Issues
-Operating System: reeBSD 9.0-RELEASE - amd64
+Operating System: FreeBSD 9.0-RELEASE - amd64
PHP Version: 5.4.4
Block user comment: N
Private report: N
New Comment:
correct misspelled OS
Previous Comments:
------------------------------------------------------------------------
[2012-07-02 18:23:01] fabrizio at queensboro dot com
Very interesting.
Thank you for your link, I always assumed that this was an issue for old
languages and that new ones would have corrected the conversion to integer
using
some sort of checking against the "to_string" (I am saying this without knowing
what it takes or what the code looks like).
As you can see here, the code knows that the value is a float(895), without
decimals, so the integer should be the same, else I would expect an output like
float(894.99999999...) during the var_dump.
<?php
$grand_total = '8.9500';
var_dump(
$grand_total,
$grand_total*100,
round($grand_total*100),
intval($grand_total*100)
);
?>
string(6) "8.9500"
float(895)
float(895)
int(894)
------------------------------------------------------------------------
[2012-07-02 16:47:24] [email protected]
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://www.floating-point-gui.de/
Thank you for your interest in PHP.
You are going to want to round() and not truncate here.
------------------------------------------------------------------------
[2012-07-02 16:30:12] fabrizio at queensboro dot com
Description:
------------
Converting from a float to an integer doesn't always return the correct values.
Try this code:
<?php
$grand_total = 8.9500;
$amount = intval($grand_total*100);
var_dump($amount, $grand_total*100, (int)($grand_total*100));
?>
This will output:
int(894)
float(895)
int(894)
when I would expect:
int(895)
float(895)
int(895)
Test script:
---------------
<?php
$grand_total = 8.9500;
$amount = intval($grand_total*100);
var_dump($amount, $grand_total*100, (int)($grand_total*100));
?>
Expected result:
----------------
int(895)
float(895)
int(895)
Actual result:
--------------
int(894)
float(895)
int(894)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=62465&edit=1