Dividing long by long returns 0 [duplicate] - java

This question already has answers here:
Is "long x = 1/2" equal to 1 or 0, and why? [duplicate]
(6 answers)
Closed 9 years ago.
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

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);

You are doing integer division! Since totaloccupied is smaller than totaldrive, the division of both gives the answer 0. You should convert to double first:
double percentageUsed = 100.0 * totalOccupied / totalDrive;
Note that adding the decimal point to the 100 ensures it is treated as a double.

That will be evaluated left to right, the first integer division will return 0 (e.g. 8/10 evaluates to 0). Either convert values to floats or do 100*a/b. Floats will give you a more precise result.

Related

Why does 1 / 2 == 0 using double? [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 6 years ago.
I'm a high school student currently getting ready for a state academic meet(UIL). I have a problem and I've looked everywhere and can't seem to find an answer! Why does this print out 0.0?
double d = 1/2;
System.out.println(d);
It's because of the data type.
When you do 1/2 that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero).
If you convert any one of them to double, you'll get a double result.
double d = 1d/2;
or
double d = 1/2.0;
1 and 2 are both integers, so 1 / 2 == 0. The result doesn't get converted to double until it's assigned to the variable, but by then it's too late. If you want to do float division, do 1.0 / 2.
It's because 1 and 2 are int values, so as per the java language spec, the result of an arithmetic operation on int operands is also int. Any non-whole number part of the result is discarded - ie the decimal part is truncated, 0.5 -> 0
There is an automatic widening cast from int to double when the value is assigned to d, but cast is done on the int result, which is a whole number 0.
If "fix" the problem, make one of the operands double by adding a "d" to the numeric literal:
double d = 1d/2;
System.out.println(d); // "0.5"
As per the language spec, when one of the operands of an arithmetic operation is double, the result is also double.
Cause result of 1/2 = 0 and then result is parsing to double. You're using int instead of double.
I think it should be ok:
double d = 1/2.0;
System.out.println(d);
Sorry for weak english

Get the next higher integer value in java [duplicate]

This question already has answers here:
How to round up the result of integer division?
(18 answers)
How to round up integer division and have int result in Java? [duplicate]
(9 answers)
Closed 4 years ago.
I know I can use Math.java functions to get the floor, ceil or round value for a double or float, but my question is -- Is it possible to always get the higher integer value if a decimal point comes in my value
For example
int chunkSize = 91 / 8 ;
which will be equal to 11.375
If I apply floor, ceil or round to this number it will return 11 I want 12.
Simply If I have 11.xxx I need to get 12 , if I have 50.xxx I want 51
Sorry The chunkSize should be int
How can I achieve this?
Math.ceil() will do the work.
But, your assumption that 91 / 8 is 11.375 is wrong.
In java, integer division returns the integer value of the division (11 in your case).
In order to get the float value, you need to cast (or add .0) to one of the arguments:
float chunkSize = 91 / 8.0 ;
Math.ceil(chunkSize); // will return 12!
ceil is supposed to do just that. I quote:
Returns the smallest (closest to negative infinity) double value that
is greater than or equal to the argument and is equal to a
mathematical integer.
EDIT: (thanks to Peter Lawrey): taking another look at your code you have another problem. You store the result of integer division in a float variable: float chunkSize = 91 / 8 ; java looks at the arguments of the division and as they are both integers it performs integer division thus the result is again an integer (the result of the division rounded down). Now even if you assign this to the float chunkSize it will still be an integer(missing the double part) and ceil, round and floor will all return the same value. To avoid that add a .0 to 91: float chunkSize = 91.0 / 8;. This makes one of the arguments double precision and thus double division will be performed, returning a double result.
If you want to do integer division rounding up you can do
x / y rounded up, assuming x and y are positive
long div = (x + y - 1) / y;
In your case
(91 + 8 - 1) / 8 = 98 / 8 = 12
This works because you want to round up (add one) for every value except an exact multiple (which is why you add y - 1)
Firstly, when you write float chunkSize = 91 / 8 ; it will print 11.0 instead of 11.375
because both 91 and 8 are int type values. For the result to be decimal value, either dividend or divisor
or both have to be decimal value type. So, float chunkSize = 91.0 / 8; will result 11.375 and
now you can apply Math.ceil() to get the upper value. Math.ceil(chunkSize); will result in 12.0

Double to int rounding normal way from .5 [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
I'm making calculation and for that I'm using the following expression:
Player.targetx = (int) (((e.getX() - Frame.x)/(Screen.myWidth/World.worldWidth))-8);
For example:
if the values are (((103 - 40)/(1184/15))-8) the double answer is around -7.20186. Player.targetx still gets value of -8.
Why's that? I would like to make it so that -7.5 gives me answer of -8 and anything like -7,499999 gives answer of -7.
Casting to int always truncates towards 0. To round, you can use Math.round() instead. However, that always rounds halves up:
class Test {
public static void main(String[] args) {
System.out.println(Math.round(-7.7)); // -8
System.out.println(Math.round(-7.5)); // -7
System.out.println(Math.round(-7.2)); // -7
System.out.println(Math.round(+7.2)); // 7
System.out.println(Math.round(+7.5)); // 8
System.out.println(Math.round(+7.7)); // 8
}
}
Are you sure you want to round halves away from zero? If so, Math.round() won't quite do what you want. You could write your own method though:
public static long customRound(double x) {
return x >= 0 ? (long) (x + 0.5)
: (long) (x - 0.5);
}
This will always round away from zero, by either adding or subtracting 0.5 first (depending on the sign) and then truncating towards 0. That produces the same values as before, except that -7.5 is rounded to -8.
EDIT: I suspect the remaining problem is almost certainly due to the division being performed in integer arithmetic. We don't know the types of any of your values, but I suspect they're all int, which would lead to that problem. If you make either of the operands of the division double, it will perform the division in double arithmetic instead. The easiest way to do that - which would also increase readability - is probably to extract some of the expressions to separate variables, and cast where necessary:
double xDifference = e.getX() - Frame.x;
double widthRatio = Screen.myWidth / (double) World.worldWith;
double x = (xDifference / widthRatio) - 8;
Player.targetx = (int) Math.round(x);
If that still doesn't work, at least you'll have a much easier time seeing what's wrong.
The final cast to int causes the result to be rounded. Try changing that cast to double. Or maybe consider using a DecimalFormat for more precise formatting.

Why this equation returns zero even though it should not? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 9 years ago.
So, I'm doing a fighting game in java and I have this equation that always returns zero.
int x = 90/100*300;
It should be 270 but it returns zero. :|
You're doing integer calculation, so 90/100 results in 0.
If you write it 90.0/100*300, the calculations will be done with doubles (then you'll need to cast it back to int if you want).
The problem here is it first divides 90/100 which is actually 0.9 however since it is an int type the value is 0 and then when you multiply 0 with 300 the output is 0.
90/100 is 0 remainder 90.
You can fix this by re-arranging the values
int x = 90 * 300 / 100; // 270
Do the multiplications before the divisions and as long as you don't get an overflow, this will be more accurate.
Java in this case carries out the multiplication/division in order.
It also interpretes each number as integers.
So, 90/100 = 0.9 and it gets truncated to 0.
and 0 * 300 = 0.
So you end up with 0
You use integer datatype you use float or double datatype and get proper answer of this equation. Integer datatype only decimal value answer return but float and double datatype return answer with floating point then must use float or double datatype in this equation.
I guess you want like this equation, try this
int x = (90/100)*300;

Why does the division of two integers return 0.0 in Java? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));

Categories

Resources