php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64307 Floating point error
Submitted: 2013-02-27 09:31 UTC Modified: 2013-02-27 14:46 UTC
From: sokkis at gmail dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.4.12 OS: Gentoo linux
Private report: No CVE-ID: None
 [2013-02-27 09:31 UTC] sokkis at gmail dot com
Description:
------------
Floating point rounded when print, but won't on subtraction.

Test script:
---------------
<?php
    $n1 = 905000;
    $n2 = 0.27;
    $ertek =$n1*$n2;
    $egesz = round( $ertek );
    $eredmeny = $ertek-$egesz;
    echo "$ertek - $egesz = $eredmeny\n";

    $n1 = 905000;
    $n2 = 0.27;
    $ertek =$n1*$n2;
    $egesz = (int) $ertek;
    $eredmeny = $ertek-$egesz;
    echo "$ertek - $egesz = $eredmeny";


Expected result:
----------------
244350 - 244350 = 0
244350 - 244350 = 0

Actual result:
--------------
244350 - 244350 = 2.9103830456734E-11
244350 - 244350 = 2.9103830456734E-11

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-02-27 09:42 UTC] pajoye@php.net
-Status: Open +Status: Not a bug
 [2013-02-27 09:42 UTC] pajoye@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.


 [2013-02-27 09:46 UTC] sokkis at gmail dot com
"Floating point values have a limited precision"

It's ok, but why not:
244350,00000000... - 244350 = 2.9103830456734E-11
the output?

So, if floating point variable has limited precision, it has it if echod, and has 
if make subractions, or any other.
 [2013-02-27 14:46 UTC] nikic@php.net
@sokkis: I don't quite understand what you are asking, but maybe you are looking for the "precision" ini option, which controls with how much precision floats will be displayed when converted to string. See here for an example: http://codepad.viper-7.com/o4M9q3
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Dec 27 02:01:29 2024 UTC