Question

I want to store 1.222 in the variable a.But when i print it is showing me 1.222000 which

means that the variable a is stored as 1.222000.But i want to store the value as 1.222 in

a. and also i want only 1.22 to be copied to b when assign a=b. Please help me to

understand how to do it.

int main()
{
    float a=1.222,b;
    b=a;//(but b=1.22 and not b=1.222) how to cut the last number 2
    printf("%f\t%f",a,b);
    return 0;
}
Was it helpful?

Solution

You can't simply tell a float to lose some digits of precision during an assignment, you'll have to do some type casting to get the intended result. For instance, to preserve only 2 digits of precision:

int main()
{
    float a=1.222,b;
    b= ((long)(a * 100)) / 100.0;
    printf("%f\t%f",a,b);
    return 0;
}

OTHER TIPS

You can't easily change the storage value, as that's the amount of allocated memory, and that's determined by the data type and system. To print two decimal places, use

printf("%.2f, %.2f", a, b);

You can't change out it is stored and your issue has nothing to do with how it is stored. You have a printing issue.

If you want to remove the extra zeroes, change %f to %g. But this will print 1.222.

If you want to print 1.22 and not 1.222 then change it to %.2f instead of %f.

If you want to round the number itself:

b=round(100*a)/100;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top