How to convert int to float in C?
I am trying to solve:
int total=0, number=0; float percentage=0.0; percentage=(number/total)*100; printf("%.2f", percentage);
If the value of the number is 50 and the total is 100, I should get 50.00 as percentage and that is what I want. But I keep getting 0.00 as the answer and tried many changes to the types but they didn't work.
Integer division truncates, so
(50/100) results in 0. You can cast to
double) or multiply with
float precision) first,
double percentage; // ... percentage = 100.0*number/total; // percentage = (double)number/total * 100;
float percentage; // ... percentage = (float)number/total * 100; // percentage = 100.0f*number/total;
Since floating point arithmetic is not associative, the results of
(double)number/total * 100 may be slightly different (the same holds for
float), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.
Read more... Read less...
integer division in C truncates the result so
50/100 will give you
If you want to get the desired result try this :
No, because you do the expression using integers, so you divide the integer 50 by the integer 100, which results in the integer 0. Type cast one of them to a
float and it should work.
You are doing integer arithmetic, so there the result is correct. Try
%f expects a
double not a
float. By pure luck that is converted here, so it works out well. But generally you'd mostly use
double as floating point type in C nowadays.
I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.
This should give you the result you want.
double total = 0; int number = 0; float percentage = number / total * 100 printf("%.2f",percentage);
Note that the first operand is a double