Divide returns 0 instead of float

I was very surprised when I found out that my code is not working, so I created a console application to see where the problem is and I was even more surprised when I saw that the code below returns 0

    static void Main(string[] args)
    {
        float test = 140 / 1058;
        Console.WriteLine(test);
        Console.ReadLine();
    }

      

I am trying to get the result in% and put it on the stroke (value (140/1058) * 100) in my application, the second value (1058) is actually a ulong-type in my application, but that doesn't seem to be a problem.

Question: where is the problem?

0


a source to share


4 answers


This will work as you expect ...

float test = (float)140 / (float)1058;

      



By the way, your code works fine for me (prints 0.1323251 to console).

+3


a source


You use integer arithmetic and then convert the result to float. Instead of floating point arithmetic:



float test = 140f / 1058f;

      

+8


a source


The problem is that you are dividing integers, not floating. Only the result is a float. Change the code as follows

float test = 140f / 1058f;

      

EDIT

John mentioned that there is an Oolong type variable. If this is the case then just use the casting
ulong value = GetTheValue();
float test = 140f / ((float)value);

      

Note, there is a possible loss of precision here as you go from ulong to float.

+4


a source


The division performed is a whole division. Replace

float test = 140 / 1058;

      

from

float test = 140f / 1058; 

      

for forced division with floating point.

In general, if you have

int x;
int y;

      

and want to do floating point division, then you have to specify either float x

or y

float as in

float f = ((float) x) / y;

      

+2


a source







All Articles