"Snapping" to certain "precision"

Started by
2 comments, last by nullsquared 16 years, 1 month ago
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?
Advertisement
Why not round the number, divide by units (and cast the result to int), and multiply the result by units?
#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.
Quote:Original post by DevFred
#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.


Got it [smile].

Thanks.

This topic is closed to new replies.

Advertisement