• Advertisement

Archived

This topic is now archived and is closed to further replies.

How to round a floating point number???

This topic is 6498 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, anyone knows how to write a function to round a floating point number to a specified decimal accuracy??.. thanks..

Share this post


Link to post
Share on other sites
Advertisement
Yeah,

add 0.5f and then cast to an integer.

rounded integer = (int)(floating point number + 0.5f)

(you should use the c++ style cast when you can ofcourse, but this should work too).

Jaap Suter

Share this post


Link to post
Share on other sites
thanks.. I got it..

float ROUND(const float value, const int accuracy)
{
double integer, fraction;

// get fraction and integer components
fraction = modf(value, &integer);

return(float(integer + (float(int(fraction*pow(10,accuracy)))) / pow(10, accuracy) ) );
} // end float ROUND

Share this post


Link to post
Share on other sites
Oops, It seems I didn''t read your original question very well. I only read the topic and gave an answer on that. Sorry.

It seems like you found the answer somewhere else already.

Jaap Suter

Share this post


Link to post
Share on other sites

  • Advertisement