Public Group

# "Snapping" to certain "precision"

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

## Recommended Posts

Very basic problem here, but I just can't wrap my head around it. Maybe I'm too tired or something :( Anyways, say I have some "precision" defined:
float units = 1;

Now, how do I "snap" some arbitrary float to this precision? For example:
float a = 1.8; // in the above case, this should "snap" to 2
units = 10;
// now a show "snap" to 0

Ideas? Any help is really appreciated [smile] EDIT: Hm. Just had a second thought:
float div = a / units;
div = (int)(a + 0.5);
float snapped = div * units;

Did I get that right?

##### Share on other sites
Why not round the number, divide by units (and cast the result to int), and multiply the result by units?

##### Share on other sites
#include <cmath>float snapped = floor(a/units + 0.5f)*units;

Don't cast float to int, you can get overflows when the float value is too large.

##### Share on other sites
Quote:
 Original post by DevFred#include float snapped = floor(a/units + 0.5f)*units;Don't cast float to int, you can get overflows when the float value is too large.

Got it [smile].

Thanks.

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
16
5. 5

• 14
• 29
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631773
• Total Posts
3002271
×