We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › newbie q: floating point round
Page Index Toggle Pages: 1
newbie q: floating point round? (Read 1236 times)
newbie q: floating point round?
Oct 25th, 2006, 8:40pm
 
Hi all,
I'm trying to find a round function that will take the original float, and the number of places after decimal point for rounding. Example:

round(12.34556 , 2) -> 12.35

All i seem to find is a round function that returns an integer, not a floating point one. Any ideas?
Re: newbie q: floating point round?
Reply #1 - Oct 25th, 2006, 10:11pm
 
This mostly works. Unfortunately it doesn't round the number up if the next decimal place is over 5.

e.g. 1.234 to 2dp is 1.23, whereas 1.236 should be 1.24, but this gives 1.23 still.

Code:
float round(float val, int dp)
{
return int(val*pow(10,dp))/pow(10,dp);
}
Re: newbie q: floating point round?
Reply #2 - Oct 26th, 2006, 1:58pm
 
So, you implemented a truncation. It may work for what I'm doing! Thanks!
Re: newbie q: floating point round?
Reply #3 - Oct 29th, 2006, 1:55pm
 
it should be noted that even when you 'round' a floating point number, it may not stay rounded.. floating point means that the numbers aren't stored per their decimal places, so a rounded 12.34566 to two places might come out as 12.3500071 or something like that.

the only way to truly fix the decimal places is to store things as integers, and divide them at the last minute by their decimal place.

and if you're just trying to do this for formatting text (the only way you'll get properly fixed decimal places) use the nf() function.
Re: newbie q: floating point round?
Reply #4 - Oct 30th, 2006, 8:11pm
 
Exactly, I needed it for formatting purposes, thanks.
Page Index Toggle Pages: 1