why is java math.round always rounding down? [duplicate] - java

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|.

Related

Dividing float by double vs dividing double by double in java [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
When I tried the following codes in Java:
System.out.println("0.1d/0.3d is " + 0.1d/0.3d)
System.out.println("0.1f/0.3d is " + 0.1f/0.3d)
I get the following output:
0.1d/0.3d is 0.33333333333333337
0.1f/0.3d is 0.3333333383003871
If float/double should get a double then float/double should be same with double/double in this case.
Just execute the below code to see binary string of number you want to check for:
System.out.println(Long.toBinaryString(Double.doubleToLongBits(0.1d)));
System.out.println(Integer.toBinaryString(Float.floatToIntBits(0.1f)));
Output:
11111110111001100110011001100110011001100110011001100110011010
111101110011001100110011001101
And you see the difference in float bits and double bits. so we can't get the same result for float/double and double/double for a longer precision values .
yes "milbrandt" said right when we are converting float quantity into double by implicit typecasting some information at decimal point will differ. That's why it is showing the different result while dividing float/ double.
As you probably know, double uses 64 bits to store a value but float 32 bits.
To represent significand, double uses 52 bits, and float uses 23 bits. Thus double can give 15 digit precision at most, and float can give 7.
If you do float / double, you actually try to divide a floating point with 7 digit precision at most (far to exact) by a floating point with 15 digit precision at most (closer to exact), and then implicitly typecast the result to a floating point with 15 digit precision. The typecast cannot restore your result from 7 digit precision to 15 digit. Therefore, the results are different though both of them are double.
initialize a double with a float and divide then. You will see the same result.
double f = 0.1f;
double d = 0.1d;
double n = 0.3d;
System.out.println("float /double = " + f/n);
System.out.println("double/double = " + d/n);
result is
float /double = 0.3333333383003871
double/double = 0.33333333333333337
The reason why you see this difference is because you don't have these exact values.
Even if we suppose 0.1d and 0.3d would be exact (which they aren't, what you can see on the result 0.33333333333333337), 0.1f is 0.10000000149011612, which makes the difference.

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

Division operation is giving me the wrong result [duplicate]

This question already has answers here:
Why does integer division code give the wrong answer? [duplicate]
(4 answers)
Closed last year.
I'm trying to divide one number by another in Processing, and I keep getting the wrong answer.
float a;
a = 3/2;
println(a);
gives me
1.0
when then answer should be 1.5.
Trying a different number,
float a;
a = 2/3;
println(a);
gives me
0.0
when the answer should be 0.666666....
Is there something I'm missing? I looked over the Processing documentation for division and it seems like I'm using the right syntax.
Like others have said, you're using integer division.
Remember that int values can't hold decimal places. So if you do a calculation that would result in decimal places, those values are truncated and you're left with only the whole number part (in other words, the integer part).
int x = 1;
int y = 2;
int z = x/y; //0
int x = 5;
int y = 2;
int z = x/y; //2
You're using int literal values (digits like 2 and 3), and those don't have decimal places, so Processing treats them like int values, and they obey the above rules.
If you care about the decimal places, then either store them in float or double variables:
float x = 1;
float y = 2;
float z = x/y; //.5
float x = 5;
float y = 2;
float z = x/y; //2.5
Or just use float literals by adding a decimal part:
float a = 2.0/3.0;
Processing now knows that these are float values, so you'll keep the decimal places.
Perhaps Processing is interpreting both 3 and 2 as integers. And, since you are dividing one integer by another, it is giving you integer division.
Try changing one or both to 3.0 and/or 2.0 instead.
Your division in interpreted as an integer division and will most probably follow Java integer division rules (since Processing seem to be based on Java).
Java inherits most of its division rules from C, these being explained in more details in a specific question/answer here.

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

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