|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2014-09-20 19:10 UTC] 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 PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 14:00:01 2025 UTC |
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.