Jump to content
  • Advertisement
Sign in to follow this  
nullsquared

"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.

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

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 this post


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

Share this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!