How to store a decimal value up to 2 decimal places in another variable in C?

3.3k Views Asked by At

Suppose a = 3.91900007534.
In C language, I want to store the value of the variable a in another variable, r, up to two decimal places, such that r = 3.92.
Note that I don't want to print the value up to two decimal places, I just want to store the value as I need the exact value of r for the next operation.

2

There are 2 best solutions below

2
Daniel Argüelles On

Simply, just multiply by 100, truncate the number with floorand divide by 100:

double convert( double in ){
   return floor(in*100)/100.0;
}

More generic approach:

#include <math.h>

double convert( double in, int decimals ){
   double aux = pow(10,decimals);
   return floor(in*aux)/aux;
}

As @Some programmer dude said, the above code truncates. If you wisth to round, just replace floor() by round():

double convert( double in ){
   return round(in*100)/100.0;
}

Here the code running: https://onlinegdb.com/By-a1Urf_

11
BiOS On

The quickest way I can think of doing it is using the following method, ie multiplying by 100, rounding and then dividing again by 100:

int main() 
{ 
   float number = 1.2345672; 
  
   // Setting precision to 2 digits
   number = round(number*100)/100; 
  
   printf("%g", number); 
   return 0; 
} 

Of course, if you wanted 3 decimal points, it would be 1000, rathern than 100.

So we can make a very good general function, like this:

double precisionSetter(double num, double precision) 
{ 
    return round(pow(10,precision)*num)/pow(10,precision); 
}

So you can easily choose how many decimal places you want it to:

double a = 1.234567
a = precisionSetter(a,2)

The above will round the float. If you are interested in truncating said float, use the floor() function rather than round() one.