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