Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a value of 0 when dividing 2 longs in c#

I am trying to divide the values of DriveInfo.AvailableFreeSpace & DriveInfo.TotalSize to try and get a percentage of it to use in a progress bar.

I need the end value to be an int as progressbar.value requires an int and the above methods return a long.

I have this as the values:

164660715520---AvailableFreeSpace

256058060800---TotalSize

When I try and set the progressbar.value using this method I also get an error:

progressBar1.Value=(int)(dInfo.AvailableFreeSpace/dInfo.TotalSize)*100;

When I use this code to try and get a value it just returns a 0.

label10.Text =  (((int)dInfo.AvailableFreeSpace/dInfo.TotalSize)*100).ToString();

I've even tried this and it doesn't work:

label10.Text = ((dInfo.AvailableFreeSpace/dInfo.TotalSize)*100).ToString();

I know I still have to do some formatting to get it to look good but whenever I run the code it just returns a 0.

Could it have something to do with the conversion from long to int?

like image 312
Zeratas Avatar asked Sep 23 '12 14:09

Zeratas


People also ask

How do you do real division in C?

printf("Enter dividend: "); scanf("%d", &dividend); printf("Enter divisor: "); scanf("%d", &divisor); Then the quotient is evaluated using / (the division operator), and stored in quotient . quotient = dividend / divisor; Similarly, the remainder is evaluated using % (the modulo operator) and stored in remainder .

Can you divide long in Java?

Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.


1 Answers

Integer division returns only the integer part. So 3/5 will be 0. You'll need to treat at least one of the factors as a floating point number. Try this:

label10.Text =  (((int)((double)dInfo.AvailableFreeSpace/dInfo.TotalSize)*100)).ToString();
like image 177
Tudor Avatar answered Oct 21 '22 22:10

Tudor