I have read many posts on Math.round
and DecimalFormat
etc. However I dont know how id go about correctly using either of the above within code where its more complicated than just simply declared variables.
List<Float> depthCopy = new ArrayList<>(depthAdd);
...//collection sort
...//iterate i over arraylist
if (depthCopy.get(i).equals(depthAdd.get(depthAdd.size() - 1))) {
System.out.println("Wettest year: " + (1000 + i) + " "
+ //FORMAT HERE?(depthAdd.get(depthAdd.size() - 1)));
}
}
This returns a value of: Wettest year: 2002 1146.3999
1146.3999
is correct
however I need to print this value formatted/rounded to 1 decimal place i.e:
1146.4
I have tried the following:
System.out.println("Wettest year: " + (1930 + i) + " "
+ (double)Math.round(depthAdd.get(depthAdd.size() - 1)));
It returns 1146.0
(incorrect)
Printed value im looking to get is 1146.4
. What is the best way to achieve this? Why would this way be better than other alternatives?
SOLUTION: Instead of Math.round use DecimalFormat
DecimalFormat df = new DecimalFormat("####.#");
System.out.println("Wettest year: " + (1000 + i) + " "
+ df.format((depthAdd.get(depthAdd.size() - 1)));