Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing long by long returns 0 [duplicate]

Tags:

java

I am trying to calculate % of used diskspace in Windows and totaldrive denotes total diskspace of c drive in Long and freedrive dentoes free space in Long.

 long totaloccupied = totaldrive - freedrive; 

Here calculating % of usage

 Long Percentageused =(totaloccupied/totaldrive*100);  System.out.println(Percentageused); 

The print statement returns 0. Can someone help as I am not getting the desired value

like image 581
user1815823 Avatar asked Aug 08 '13 02:08

user1815823


People also ask

How do you divide long values?

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.

How do you divide integers in Java?

Java does integer division, which basically is the same as regular real division, but you throw away the remainder (or fraction). Thus, 7 / 3 is 2 with a remainder of 1. Throw away the remainder, and the result is 2. Integer division can come in very handy.

How do you divide two variables in Java?

// Divide a literal by a literal; result is 5 int result = 10 / 2; // Divide a variable by another variable; result is 3 int a = 15; int b = 5; int result = a / b; When dividing integer types, the result is an integer type (see the previous chapter for the exact data type conversions for mathematical operations).


1 Answers

You are probably dividing a long with a long, which refers to (long/long = long) operation, giving a long result (in your case 0).

You can achieve the same thing by casting either operand of the division to a float type.

Long Percentageused = (long)((float)totaloccupied/totaldrive*100); 
like image 129
Lake Avatar answered Sep 29 '22 04:09

Lake