1

I've run into a small problem. I'm trying to remove extra decimal places in c, that will be used in calculations.

For example 67.98345, I want it to be 67.98

But not just for a printf statement. I need the double to actually be 67.98 not 67.98345

Guardian
  • 85
  • 1
  • 1
  • 3

2 Answers2

2

@mvp's answer is okay, but it has a minor problem. The intermediate value of the multiplication can overflow the double if x is close to the maximum double magnitude. An alternative that fixes this problem is:

double intpart, fracpart;

fracpart = modf(x, &intpart);
x_rounded = intpart + round(fractpart * 100) / 100;
Gene
  • 42,664
  • 4
  • 51
  • 82
0

This will round to the nearest value:

double x_rounded = round(x*100)/100;

For completeness, these will round down or up:

double x_rounded_down = floor(x*100)/100;
double x_rounded_up   = ceil (x*100)/100;
mvp
  • 94,368
  • 12
  • 106
  • 137
  • Note you must `#include ` for this to be correct, and that if x is near the maximum double magnitude you can get overflow of the intermediate result so that the answer will be +-inf. – Gene Mar 03 '13 at 03:15
  • Considering that max double value is `1.7977e+308`, you only encounter this problem if `x > 1.7977e+306` - which would be fine with most people – mvp Mar 03 '13 at 03:44