php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68065 In some cases intval after floatval gives unexpected results
Submitted: 2014-09-20 19:10 UTC Modified: 2014-09-20 19:55 UTC
From: kstirn at gmail dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: Irrelevant OS: Windows
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: kstirn at gmail dot com
New email:
PHP Version: OS:

 

 [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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-09-20 19:47 UTC] rasmus@php.net
-Status: Open +Status: Not a bug
 [2014-09-20 19:47 UTC] 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:55 UTC] rasmus@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 02:01:30 2024 UTC