Example Input : 12345.1
Desired ouput on 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);
}
});
Actual result
System.out.println(formattedText) : 12,345.10 //OK
totalAmountDueTextField.setText(formattedText) : 12345.1 //This is the problem.
And also how to set the initial value to 0.00 (current is 0.0) ?