Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int to float in C?

Tags:

c

int

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.

like image 274
Jack Avatar asked Nov 23 '12 13:11

Jack


People also ask

Can we convert int to float in C?

int total=0, number=0; float percentage=0.0; percentage=((float)number/total)*100; printf("%. 2f", percentage); Add (float) before the variable name when you use.

Can integer convert to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.

How do you convert an integer variable into a float?

Integer and Float Conversions To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.

Can we use %d for float in C?

So, you can see here that %d is used for integers, %f for floats and %c for characters. As simple as that! %. 2f means that the variable to be printed will be of type float and '.


2 Answers

Integer division truncates, so (50/100) results in 0. You can cast to float (better double) or multiply with 100.0 (for double precision, 100.0f for float precision) first,

double percentage; // ... percentage = 100.0*number/total; // percentage = (double)number/total * 100; 

or

float percentage; // ... percentage = (float)number/total * 100; // percentage = 100.0f*number/total; 

Since floating point arithmetic is not associative, the results of 100.0*number/total and (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.

like image 91
Daniel Fischer Avatar answered Sep 19 '22 14:09

Daniel Fischer


integer division in C truncates the result so 50/100 will give you 0

If you want to get the desired result try this :

((float)number/total)*100 

or

50.0/100 
like image 41
Omkant Avatar answered Sep 17 '22 14:09

Omkant