I am displaying average in JTextField
, and I want to round it up to two decimal places to use my code below, to create BarChart
using JFreeChart. I have seen many tutorials about that, but I don't know how to implement any of it in my code.
That is my list:
List<Double> light = new ArrayList<Double>();
for (Measurement measurement : readMeasurements) {
light.add(Double.parseDouble(measurement.getLight()));}
double averageLight = Utils.calculateAverage(light);
textLight.setText(averageLight+" ...");
That is my Utils
that calculate average:
public static double calculateAverage(List<Double> list){
double av=0;
double sum=0;
for(double value : list){
sum+=value;
}
av = sum/list.size();
return av;
}
With that I get in textfiled output like ##.################
.
And here is part of code that creates BarChart
using JFreeChart. It works when in JTextField
output is ##.##
:
String temperature = textTemp.getText();
String light = textLight.getText();
String vcc = textVcc.getText();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.setValue(new Double (temperature), "Measurements", "Temperature");
dataset.setValue(new Double (light), "Measurements", "Light");
dataset.setValue(new Double (vcc), "Measurements", "Vcc");
How can I make any changes to that code to make an output in JTextField
like ##.##
?
textLight.setText(String.format("%.2f", averageLight));
The "%.2f"
is a format string, and means "format an argument as a floating point number with two decimal places". For more detail on what characters you can use in one of those, and what they each mean, refer to http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html