小数格式不限制小数点后两位

Decimal format not limiting values to two decimal places

我正在编写一个 java gui 程序来转换不同的测量单位。我想将结果的输出限制在小数点后两位,这样看起来更整洁,但我一直在努力让它工作。下面是我的代码,请有人帮忙。

if (text.isEmpty() == false) {

            double value = Double.parseDouble(text);

            // the factor applied during the conversion
            double factor = 0;

            // the offset applied during the conversion.
            double offset = 0;


            // Setup the correct factor/offset values depending on required conversion
            switch (combo.getSelectedIndex()) {

            case 0: // inches/cm
                factor = 2.54;
                break;

            case 1: // miles/km
                factor = 1.60;
                break;

            case 2: // pounds/kilograms
                factor = 0.45;
                break;

            case 3: // gallons/Litres   
                factor = 4.54;
                break;

            case 4: // feet/meters  
                factor = 0.30;
                break;

            case 5: //  celsius/kelvin
                factor = 1;
                offset=273.15;
                break;

            case 6: //  acres/hectare   
                factor = 2.471;
                break;
            }

            double result = 0;


            if(reverseCheck.isSelected() == true) {
                result = factor / value - offset;


            }else {
                result = factor * value + offset;
            }



            count++;
            labelCount.setText("Conversion Count: "+count);


            label.setText(Double.toString(result));

            DecimalFormat decFormat = new DecimalFormat("0.00");
            decFormat.format(result);

我是编程新手,所以如果您能解释为什么这段代码不起作用,我们将不胜感激。我的输出当前有太多小数位,我需要它只有 2 位小数。

I am new to programming

所以首先要学会的是如何简化问题。

I want to limit the output of the result to two decimal place so it looks neater

因此,忘掉应用程序的其余部分并了解如何做到这一点:

double value =  123.45678;
DecimalFormat decFormat = new DecimalFormat("0.00");
String formatted = decFormat.format(value);
System.out.println( formatted );

I am writing a java gui program which converts different units of measurement.

这与你的问题无关。从上面的示例中可以看出,您首先使用硬编码数据测试了一个新概念。

一旦你开始工作,你就会担心动态获取你想要格式化的 "value" 的数学计算。

My output currently is too many decimal places

label.setText(Double.toString(result));
DecimalFormat decFormat = new DecimalFormat("0.00");
decFormat.format(result);

你看到上面代码的问题了吗?

  1. 在格式化结果之前设置标签的文本
  2. 您没有将格式化文本分配给变量,因此最后一条语句不会执行任何操作。