示例输入:12345.1
totalAmountDueTextField上的所需输出:12,345.10
TextField totalAmountDueTextField = new TextField("0.00");
Pattern validDoubleText = Pattern.compile("-?\\d*(\\.\\d{0,2})?");
TextFormatter<Double> textFormatter = new TextFormatter<>(new DoubleStringConverter(), 0.00,
change -> {
String newText = change.getControlNewText() ;
if (validDoubleText.matcher(newText).matches()) {
return change ;
} else return null ;
});
totalAmountDueTextField.setTextFormatter(textFormatter)
totalAmountDueTextField.focusedProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue o, Object oldVal, Object newVal) {
DecimalFormat format = new DecimalFormat("#,##0.00");
String formattedText = format.format(Double.parseDouble(totalAmountDueTextField.getText()));
System.out.println(formattedText);
totalAmountDueTextField.setText(formattedText);
}
});
实际结果
System.out.println(formattedText):12,345.10 //确定
totalAmountDueTextField.setText(formattedText):12345.1 //这就是问题。
还有如何将初始值设置为0.00(当前为0.0)?
答案 0 :(得分:0)
使用这个可能对你有所帮助
totalAmountDueTextField.setText(new BigDecimal(totalAmountDueTextField.getText())。 setScale(2,RoundingMode.FLOOR));