Reputation: 2849
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!
Upvotes: 5
Views: 2386
Reputation: 961
Both of the values are integers, so they are rounded down to 7. As the result of integer division is an integer you need to make sure you divide doubles / floats as the results of these divisions are doubles / floats which can deal with the decimal parts of the numbers
Even though you specified a double to put the result of the division into what you are actually putting in is an integer, dividing a double means the result is a double and so the answer contains the correct results.
Upvotes: 1
Reputation: 20112
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).
Upvotes: 3
Reputation: 32391
That's because 15 / 7
is 2
as it is returning the integer part of the dividing operation. If you need float values operations, do something like this: 15f / 7
.
Upvotes: 1
Reputation: 51935
15/7 performs an integer division, which rounds down to the nearest integer.
15/7 = 2 + 1/7 -> gets rounded to 2
It doesn't matter that you defined y as a double, the division didn't take that into account, since it was using 2 integer literals.
Upvotes: 1
Reputation: 26819
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)
Upvotes: 3
Reputation: 382142
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.
Upvotes: 3