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.
How to store a decimal value up to 2 decimal places in another variable in C?
3.3k Views Asked by Imtiaz At
2
There are 2 best solutions below
11
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.
Simply, just multiply by 100, truncate the number with
floorand divide by 100:More generic approach:
As @Some programmer dude said, the above code truncates. If you wisth to round, just replace
floor()byround():Here the code running: https://onlinegdb.com/By-a1Urf_