Double计算错误的浮点数

1 java jtextfield

我目前正在开发一个项目,其中包含屏幕上某些值的计算:

double calculatedValue;
double calculatedValue2;
private JTextField firstUnity;
private JTextField secondUnity;
firstUnity = new JTextField();
firstUnity.setEditable(false);
secondUnity = new JTextField();
secondUnity.setEditable(false);
add(firstUnity);
add(secondUnity);

public void calculate(){
    calculatedValue = 10/2.5;
    calculatedValue2 = 10/2.55;
    firstUnity.setText(String.valueOf(calculatedValue));
    secondUnity.setText(String.valueOf(calculatedValue2));
}
Run Code Online (Sandbox Code Playgroud)

对于firstUnityTextField显示4为预期.不幸的secondUnity节目"5686274509807".

有人可以向我解释这种解释的原因是什么?

谢谢你的帮助

Neu*_*ron 5

JTextField太短了,无法展示double.您可以通过确保标签足够宽或通过使用以下方法减少显示的小数位数来解决此问题DecimalFormat:

public static final DecimalFormat DISPLAY_FORMAT = new DecimalFormat("#.####");

public void calculate(){
    calculatedValue = 10/2.5;
    calculatedValue2 = 10/2.55;
    firstUnity.setText(FORMAT.format(calculatedValue));
    secondUnity.setText(FORMAT.format(calculatedValue2));
}
Run Code Online (Sandbox Code Playgroud)

您可以通过增加/减少构造函数参数中的#字符数来调整显示的小数位数DecimalFormat.