php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #40892 floating point rounding issue
Submitted: 2007-03-22 14:13 UTC Modified: 2007-03-22 14:42 UTC
From: fizz at beyond dot hjsoft dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.2.1 OS: linux, solaris
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: fizz at beyond dot hjsoft dot com
New email:
PHP Version: OS:

 

 [2007-03-22 14:13 UTC] fizz at beyond dot hjsoft dot com
Description:
------------
When printing out a floating point number using printf (or storing 
it with sprintf, or casting it as an int) it gives an incorrect 
number.  This appears to be due to floating point math being 
inaccurate.

Reproduce code:
---------------
<?php
$val = 309;
for ($x = 0; $x < 950; $x++)
        $val += 0.001;
var_dump($val);
echo $val . "\n";
$val = $val * 100;
var_dump($val);
echo $val . "\n";
printf ("%d\n", $val);
echo (int)$val . "\n";
?>


Expected result:
----------------
float(309.95)
309.95
float(30995)
30995
30995
30995


Actual result:
--------------
float(309.95)
309.95
float(30995)
30995
30994
30994


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-03-22 14:23 UTC] tony2001@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://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.


 [2007-03-22 14:42 UTC] fizz at beyond dot hjsoft dot com
I very much understand that, my concern was more of a consistency 
issue between how echo and var_dump does it (which outputs the 
correct information) and how printf/sprintf does (which gives 
incorrect output).
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Apr 28 15:01:31 2024 UTC