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

24,405

Solution 1

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

Solution 2

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

Solution 3

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

Share:
24,405
johnfis12
Author by

johnfis12

Updated on July 09, 2022

Comments

  • johnfis12
    johnfis12 almost 2 years

    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.

  • Joseph Quinsey
    Joseph Quinsey about 10 years
    In edge cases, printf() can give different results on different systems. For example, gcc uses Banker's Rounding, but not MSVC 2010.
  • Eric Postpischil
    Eric Postpischil about 10 years
    I do not think it will always be the closest. The multiplication by 100 will introduce error that might change x.xx499999… to xxx.5, which round could increase, when the desired result would be a decrease.
  • chux - Reinstate Monica
    chux - Reinstate Monica about 10 years
    @Eric Postpischil I agree with that point. Perhaps modf() may help? I'll cogitate on your idea.