RE: [PHP] Peculiar number_format() behaviour

From: Date: Mon, 22 Mar 2004 11:24:22 +0000
Subject: RE: [PHP] Peculiar number_format() behaviour
Groups: php.general 
Request: Send a blank email to php-general+get-181119@lists.php.net to get a copy of this message
On 22 March 2004 10:31, Paul Hopkins wrote: > Here's the code: > > <?php > $a = 676.6; > $b = 0.175; > > $y = $a * (1 + $b); > echo("y: " . $a . " * (1 + " . $b . ") = $y<BR>"); > > $z = $a + ($a * $b); > echo("z: " . $a . " + ( " . $a . " * " . $b . ") = > $z<BR>"); > > echo("number format(y)=".number_format($y, 2)."<BR>"); > echo("number format(z)=".number_format($z, 2)."<BR>"); > > > > > Here's the output: > > y: 676.6 * (1 + 0.175) = 795.005 > z: 676.6 + ( 676.6 * 0.175) = 795.005 > number format(y)=795.01 > number format(z)=795.00 This is because of the inherent minor imprecision in the way floating point numbers are represented in a computer -- please see the big fat note headed "Floating point precision" at http://www.php.net/manual/en/language.types.float.php. You should never rely on the absolute accuracy of floating point numbers -- even very simple calculations can be off by an infinitesimal but nonetheless significant amount (for example, 10.0/3*3 almost never equals 10.0 ;). Cheers! Mike --------------------------------------------------------------------- Mike Ford, Electronic Information Services Adviser, Learning Support Services, Learning & Information Services, JG125, James Graham Building, Leeds Metropolitan University, Beckett Park, LEEDS, LS6 3QS, United Kingdom Email: m.ford@leedsmet.ac.uk Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211

« previous php.general (#181119) next »