简体   繁体   中英

I don't know how to implement math.round() or any other solution to get ##.## in JTextField

I am displaying average in JTextField and I want to round it up to two decimal places to use my code above, 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 cod e that creates BarChart using JFreeChart. It works when in e 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

You can use a decimal formatter for the specified pattern.

DecimalFormat df = new DecimalFormat("#,##0.00");
textLight.setText(df.format(averageLight));

If you need to read the value from the textfield you can use the same formatter to parse text value. So, you text value becomes readable and writable. Take care about handling ParseException and the locale specific symbols.

NumberFormat is probably better than String.format for this purpose:

NumberFormat nf = NumberFormat.getInstance();
nf.setRoundingMode(RoundingMode.HALF_UP);
nf.setMaximumFractionDigits(2);
textLight.setText(String.format(nf.format(averageLight));

Do leave a comment if you should have further problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM