can someone explain to me why the output for this:
double y = 15/7;
DecimalFormat first = new DecimalFormat("#.###");
System.out.println(y);
String format_string = first.format(y);
System.out.println(format_string);
Is this:
2.0
2
(Which is wrong)
However, when I change 15/7 to
15.0/7.0
It gives me the correct answer
2.142857142857143
2.143
Explanation please?
Thank you!
Numbers without a dot are Integers so 15/7 is an integer-operation and the result is 2 (divistion without remainder). Afterwards it gets converted to a double but keaps it's value of 2 (conversion after finishing the operation).
Numbers with dots are doubles in the first place so 15.0/7.0 is a double-operation and leads to the result you want to have (floating point division).
Replace
double y = 15/7;
with
double y = 15.0/7;
When dividing two int
, you get an int
.
See specification :
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|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.
You convert it to a double
by storing it in a double
variable but that's too late : you can't get the lost precision back. The solution is to have one of the operands being a double so that you get a double when dividing.
Division of two integers
always results in integer
- that's why you get 2
(2.0
after formatting).
Division of at least one double
gives you double
In your case 15/7
is a division of two integers and the result is an integer (incorrect result). If you change to 15/7.0
or 15.0/7
or 15.0/7.0
your result will be double
(correct result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With