Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you round a value to 2 decimal places in C?

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.

like image 737
johnfis12 Avatar asked Dec 19 '22 18:12

johnfis12


1 Answers

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

like image 174
chux - Reinstate Monica Avatar answered Dec 22 '22 06:12

chux - Reinstate Monica