note 1353 modified in function.round by irc-html

From: Date: Sat, 19 Jan 2002 12:13:00 +0000
Subject: note 1353 modified in function.round by irc-html
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-25137@lists.php.net to get a copy of this message
Here is a more detailed description, taken from http://www.progressive-comp.com/Lists/?l=php3-general&m=93230944323512&w=2 > I tried > round(11.5) and I get 12 > round(182.5) and I get 182... > > You are right. > It could be a bug in the round() function. This is normal and reflects how computers store floating point numbers. 11.5 is not actually 11.5. It is 11.49999999999999999 or 11.50000000000000000001. Floating point numbers are approximated using some level of precision. Think of 1/3. How would you write that? 0.3333333333... when do you stop? How many 3's do you need to accurately write 1/3? To be completely accurate you need an infinite amount of 3's and that just isn't feasible, so at some point you just have to say that you have enough precision. This means that round(11.5) is not defined. If you want to always round up on .5, you should add some small (less than your desired precision) value to the number you feed to round. And if you want to always round down on .5 you should substract it. eg. $fuzz = 0.00000001; echo round(11.5 + $fuzz); -Rasmus --was-- Here is a more detailed description, taken from http://www.progressive-comp.com/Lists/?l=php3-general&m=93230944323512&w=2 <PRE> > I tried > round(11.5) and I get 12 > round(182.5) and I get 182... > > You are right. > It could be a bug in the round() function. This is normal and reflects how computers store floating point numbers. 11.5 is not actually 11.5. It is 11.49999999999999999 or 11.50000000000000000001. Floating point numbers are approximated using some level of precision. Think of 1/3. How would you write that? 0.3333333333... when do you stop? How many 3's do you need to accurately write 1/3? To be completely accurate you need an infinite amount of 3's and that just isn't feasible, so at some point you just have to say that you have enough precision. This means that round(11.5) is not defined. If you want to always round up on .5, you should add some small (less than your desired precision) value to the number you feed to round. And if you want to always round down on .5 you should substract it. eg. $fuzz = 0.00000001; echo round(11.5 + $fuzz); -Rasmus </PRE> http://www.php.net/manual/en/function.round.php

« previous php.notes (#25137) next »