# In my Round() foolproof ?

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

## Recommended Posts

Hi guys, Is this foolproof: int Round(double x) { if(x > 0.0) return (int)(x+0.5); else if(x < 0.0) return (int)(x-0.5); return 0; } It seems solid but maybe I'm missing something ? Thanks.

##### Share on other sites
Well, as long as you aren't dealing with monetary values, should be fine.

##### Share on other sites
Ok, I'm just completely guessing at this and have no idea if it is or is not true. Is it possible that ".5 + ??.5 < ?? + 1"? Basically, I'm wondering if the innacurate nature of floating point will make it so that the rounding function will sometimes go the wrong way. Of course, even if true it is completely nitpicky (but you did say foolproof).

##### Share on other sites
You'll only have problems if your double values are greater than the available precision. Without looking at the IEEE specification, I'm pretty much sure your function is fine for values MAX_INT/4 and lower. You might safe all the way up to MAX_INT (after which, it dosn't really matter, because you can't convert anyway).

Quote:
 Is it possible that ".5 + ??.5 < ?? + 1"?

Because of the way floating point numbers are represented, 0.5 becomes "1/2" which can be exactly represented in binary (as "1/10").

##### Share on other sites
You may also have troubles if your double is NaN or +-INF

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 11
• 13
• 9
• 11
• ### Forum Statistics

• Total Topics
634092
• Total Posts
3015442
×