none
how to convert int to float

    Question

  • 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

    Friday, February 23, 2007 3:27 PM

Answers

  • 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:44 PM

All replies

  • 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 3:35 PM
  • 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:44 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 6:27 PM
  • int a = 4;
    int b = 25;
    float result = ((float)(a))/b;

    result is 0.16

    Grtz
    Adriaan
    Friday, February 23, 2007 11:58 PM
  • Hi,

    Thanks for your solution.

     

    Saturday, February 24, 2007 4:04 AM
  • Insead of type conversion of Variables u can simly use  function

    Convert.ToFloat(a/b);

    Saturday, February 24, 2007 7:57 AM
  • Sorry Keyu, but you posted the same wrong answer as was previously posted...
    Monday, February 26, 2007 12:06 PM
  • There is no such function as Convert.ToFloat you mentioned .
    Saturday, March 15, 2014 6:00 AM