# Floating point rounding woes

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

## Recommended Posts

Is there a good way to chop off the value of a float beyond a certain accuracy? I want to get rid of anything smaller than 0.001 but keep the rest of the value. For example, 2.1005 would become 2.100. (I'm doing this in C++, by the way.)

##### Share on other sites
For a given precision p,
Find the magnitude of your number m=⌊log10 |x|⌋
Divide the number by 10m-p
Round off
Multiply by 10m-p

Would that do?

##### Share on other sites
Yowza, that looks computationally expensive, but if there's no other way. Thanks for the reply!

##### Share on other sites
Quote:
 Original post by griminventionsYowza, that looks computationally expensive, but if there's no other way. Thanks for the reply!

There can very well be, that's just the first thing that came to my mind.

##### Share on other sites
I came to the conclusion that instead of chopping out the tiny fractions giving me problems, I can ignore values below a threshold to solve the problem effectively. But thanks for the replies!

##### Share on other sites
It's not very computation expensive. However, a float cannot represent a value like 2.1 exactly, so you will still only get an approximation of that value.

##### Share on other sites
I managed to decrease the frequency of the problem, but rounding errors are still causing trouble. I'll try the formula Fruny gave.

##### Share on other sites
Well, I ended up starting with a double, then casting to a float. It seems to have done the job. Thanks for your input, guys!

##### Share on other sites
floorf (x * 1000.0f) * 0.0001f;

##### Share on other sites
Mi mistake
floorf (x * 1000.0f) * 0.001f;

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 15
• 22
• 13
• 14
• 45