Public Group

# Cropping A Float/Double

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

## 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 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 on other sites
The simplest methods are often the best! Exactly what I wanted, thank you.

##### 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.)

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

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633703
• Total Posts
3013454
×