Share via


how to convert int to float

Question

Friday, February 23, 2007 3:27 PM

Hi all,

I have two variable, count and totalcount, both are integer

My result is declared as float,

When I perform

result = count/totalcount;

it did not return a float as it should be.

Instead, it return 0 (eg 5/25)

How can I convert it to float?

Thanks

All replies (8)

Friday, February 23, 2007 3:44 PM âś…Answered

That won't work Rizawan...

totalCount/count will still be calculated in integer precision.

The correct answer is:

float result = count / (float)totalCount;


Friday, February 23, 2007 3:35 PM

int count, totalCount;

count = 5;

totalCount = 25;

float result = Convert.ToSingle(totalCount /count );

I hope this will help.

Best Regards,

Rizwan aka RizwanSharp


Friday, February 23, 2007 6:27 PM

 Matthew Watson wrote:
That won't work Rizawan...

totalCount/count will still be calculated in integer precision.

The correct answer is:

float result = count / (float)totalCount;

Sorry Matthew,

You are right I just took the quesiton wrong as you can assume from my answer above.

Best Regards,

Rizwan aka RizwanSharp

 


Friday, February 23, 2007 11:58 PM

int a = 4;
int b = 25;
float result = ((float)(a))/b;

result is 0.16

Grtz
Adriaan


Saturday, February 24, 2007 4:04 AM

Hi,

Thanks for your solution.

 


Saturday, February 24, 2007 7:57 AM

Insead of type conversion of Variables u can simly use  function

Convert.ToFloat(a/b);


Monday, February 26, 2007 12:06 PM

Sorry Keyu, but you posted the same wrong answer as was previously posted...


Saturday, March 15, 2014 6:00 AM

There is no such function as Convert.ToFloat you mentioned .