Bug #67257 [Opn->Nab]: Edge case error when casting to integer
Edit report at https://bugs.php.net/bug.php?id=67257&edit=1
ID: 67257
Updated by: requinix@php.net
Reported by: cc at altruja dot de
Summary: Edge case error when casting to integer
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Linux
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
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.
256.4 is represented internally like 256.39999999999999998 and multiplying exposes that error.
Do a round(256.4 * 100, -1) to get your expected result.
Previous Comments:
------------------------------------------------------------------------
[2014-05-12 11:24:30] cc at altruja dot de
Description:
------------
There seems to be an oddity in an edge case of casting float to integer after multiplying it with a
multiple of 10. It only seems to occur with .4 after the decimal point, and only between 256.4 and
328.4.
Test script:
---------------
<?php
var_dump((integer) (255.4 * 100));
var_dump((integer) (256.4 * 100));
var_dump((integer) (256.3 * 100));
var_dump((integer) (327.4 * 100));
var_dump((integer) (328.4 * 100));
Expected result:
----------------
int(25540)
int(25640)
int(25630)
int(32740)
int(32840)
Actual result:
--------------
int(25540)
int(25639)
int(25630)
int(32739)
int(32840)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=67257&edit=1
Thread (2 messages)