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
Related
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
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;
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.
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 9 years ago.
I have a number of fields which take inputs, a process which happens and then fields that show the output. My issue is that for some reason math.round seems to be always rounding down instead of to the nearest integer.
Here is an example
private void method(){
int X= Integer.parseInt(XjTF.getText());
int Y= Integer.parseInt(YjTF.getText());
float Z =(X+Y)/6;
int output = Math.round(Z);
OutputjTF.setText(Integer.toString(output)+" =answer rounded to closest integer");
}
Your X and Y variables are int, so Java performs integer division, here when dividing by 6. That is what is dropping the decimal points. Then it's converted to a float before being assigned to Z. By the time it gets to Math.round, the decimal points are already gone.
Try casting X to float to force floating point division:
float Z =((float) X + Y)/6;
That will retain the decimal information that Math.round will use to properly round its input.
An alternative is to specify a float literal for 6, which will force the sum of X and Y to be cast to float before the division:
float Z = (X + Y)/6.0f;
It can't just be 6.0, because that's a double literal, and the Java compiler will complain about "possible loss of precision" when attempting to assign a double to a float.
Here's the relevant quote from the JLS, Section 15.17.2:
Integer division rounds toward 0. That is, the quotient produced for
operands n and d that are integers after binary numeric promotion
(§5.6.2) is an integer value q whose magnitude is as large as possible
while satisfying |d · q| ≤ |n|.
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) + "%"));