Rounding Float to given precision

Use trunc, round or ceil in C standard library and wondering why its output different with same spreadsheet function?

This is handy snippet to do it :

float roundMe(float f,float pres)
{
 return (float) (floor(f*(1.0f/pres) + 0.5)/(1.0f/pres));
}

How to use it :
float value = 0.7499;
roundMe(value,0.01); // return 0.75
roundMe(value,0.1); // return 0.7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s