php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42336 A bug on rounding and calculating numbers?
Submitted: 2007-08-18 11:32 UTC Modified: 2007-08-19 10:12 UTC
From: Makinen_Juha at hotmail dot com Assigned:
Status: Not a bug Package: *Math Functions
PHP Version: 5.2.3 OS: winxp/2000
Private report: No CVE-ID: None
 [2007-08-18 11:32 UTC] Makinen_Juha at hotmail dot com
Description:
------------
In the code below, i get wrong results with php 5.2.3 and 5.2.2.

The code tries to round 3 digit numbers to 2 digit numbers. Round fails at 1.225 and calculated numbers at 4.264.

Iam creating a big calculating software with this language and i hope this is my mistake :)

Reproduce code:
---------------
<?php
	for ( $i=0.01;$i<10;$i=$i+0.003 )
	{ 
		echo $i." -> ".calcRound( $i )."<br>";
		echo round($i,2)."<br>";
	}

	function calcRound( $inNumber )
	{
		$intnum = $inNumber*100;
		$intnum = (int) $intnum;

		$decnum = $inNumber*100;

		if ( $decnum - $intnum > 0.4 ) { $intnum++; }

		return $intnum / 100;
	}
?>

Expected result:
----------------
...
1.255 -> 1.26 (calculated round)
1.26 (round function)
...

...
4.264 -> 4.26 (calculated round)
4.26 (with round function)
4.267 -> 4.27 (calculated round)
...

Actual result:
--------------
...
1.255 -> 1.26 (calculated round)
1.25 (round function)
...

...
4.264 -> 4.27 (calculated round)
4.26 (with round function)
4.2670000000001 -> 4.27 (calculated round)
...

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-08-18 12:21 UTC] Makinen_Juha at hotmail dot com
Round fails at 1.255, not 1.225 :)
 [2007-08-19 10:12 UTC] johannes@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.

.
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Mon Oct 26 05:01:24 2020 UTC