Sign in to follow this  
frogtag

Cropping A Float/Double

Recommended Posts

I have 3 co-ordinates... x = 0.000001234 y = 0.000007256 y = 0.000015398 I want to crop the values to, for example, 2 decimal places. I want to be able to do this without rounding up or down, just a straight cut-off. Can anyone tell me how this is possible in Cpp please? Or if not a straight cut-off how to round up or down? Thank you

Share this post


Link to post
Share on other sites
When you say you want to crop the value to two decimal places, do you mean you want to ignore anything after the second decimal place (in which case, all three of those above numbers would be zero), or do you mean you want to locate the first two non zero values after the decimal point?

To merely chop everything off after the second decimal:

x = int(x * 100) / 100.0f

Share this post


Link to post
Share on other sites
That may look like a good solution, but it isn't quite there, unfortunately.

First, you need to check: do you want to display a truncated value, or store one?

For display, it depends on your language. In C++, you can use the .precision member function of the output stream, or the std::setprecision stream manipulator.

For storage, the calculation shown will only give you an approximate answer: you can't store the result exactly, because floating-point numbers just don't work that way. In particular, '100 * rounded_value' might not give the result you'd expect.

You should also keep in mind that rounding to 2 decimal places is different from rounding to 2 significant figures. Your sample coordinates would all round to 0 with the proposed code. (Also, "a straight cut-off" is the same thing as rounding down, for positive values.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this