Bug #68065 [Nab]: In some cases intval after floatval gives unexpected results

From: Date: Sat, 20 Sep 2014 19:55:19 +0000
Subject: Bug #68065 [Nab]: In some cases intval after floatval gives unexpected results
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-187629@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=68065&edit=1 ID: 68065 Updated by: rasmus@php.net Reported by: kstirn at gmail dot com Summary: In some cases intval after floatval gives unexpected results Status: Not a bug Type: Bug Package: Math related Operating System: Windows PHP Version: Irrelevant Block user comment: N Private report: N New Comment: Why would it be different in this case, by the way? intval() just takes the integer value and discards the fractional value. And since 1.2812, like many floating point values, cannot be represented accurately. If you crank up the precision you will see what it actually is internally: php > ini_set('precision',24); php > $a = 1.2812; php > echo $a; 1.2811999999999998944844 So when you truncate 1000 * 1.2811999999999998944844 you are obviously going to get 12811 not 12812. The other two echoes in your test are not doing truncation so they give 12812 as that is the correct display value for the float based on your chosen precision. Previous Comments: ------------------------------------------------------------------------ [2014-09-20 19:47:54] rasmus@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://www.floating-point-gui.de/ Thank you for your interest in PHP. . ------------------------------------------------------------------------ [2014-09-20 19:10:21] kstirn at gmail dot com Description: ------------ See test script - after multiplication and floatval, intval gives unexpected (wrong) result. This only seems to happen with some special initial $a floats, not in all cases. I know floating point precision cannot be trusted, but in this case it may be hard to blame it? Tested on Windows 7 and Linux (CentOS 6) with PHP 5.3.29 and 5.6.0 Test script: --------------- $a = 1.2812; $a = $a * 10000; echo "$a<br>"; $a = floatval($a); echo "$a<br>"; $a = intval($a); echo "$a<br>"; Expected result: ---------------- 12812 12812 12812 Actual result: -------------- 12812 12812 12811 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=68065&edit=1

« previous php.bugs (#187629) next »