Question

I am calculating the volume of a room and I got a number with 6 decimal places. I was wondering if I can reduce the value to only 2 decimal places. The resulting number for the volume is from 5 different variables, which I do not know if it matters in this situation.

Was it helpful?

Solution

@Rashmi solution provides a nicely rounded display of a floating point value.
It does not change the value of the original number.

If one wants to round a floating point value to the nearest 0.01 use round()

#include <math.h>
double d = 1.2345;
d = round(d * 100.0)/100.0;

Notes:

Due to FP limitations, the rounded value may not be exactly a multiple of 0.01, but will be the closest FP number a given platform allows.

When d is very close to x.xx5, (x is various digits 0-9) d * 100.0 introduces a rounding in the product before the round() call. Code may round the wrong way.

OTHER TIPS

You can use printf("%.2f", 20.233232)

There might be a round() function floating around (ha ha) somewhere in some math library (I don't have a C ref at hand). If not, a quick and dirty method would be to multiply the number by 100 (shift decimal point right by 2), add 0.5, truncate to integer, and divide by 100 (shift decimal point left by 2).

The floating point value 0.01 cannot be expressed in IEEE 754, so you still get more decimals than you asked for.

Better Way: just don't display the extra decimals in your program. I doubt you are "getting" 6 decimals; it could be the default value for a plain

printf ("too much accuracy in %f!", yourFloat);

If so, use %.2f to display.

Slightly Worse Way, depending on the numerical range and the sort of calculations you are going to do: multiply the floats by 100, round, and store as integer. 100.00% guaranteed you'll only get two digits of accuracy. Watch out when dividing (you'll loose 2 digits if not done carefully) and multiplying (you'll gain 2).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top