0

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) ?

ronald
  • 143
  • 1
  • 2
  • 11
  • maybe this will help http://stackoverflow.com/questions/12962515/right-pad-with-zeros – Ezio Feb 20 '17 at 06:24

1 Answers1

0

use this one may be helpful to you

totalAmountDueTextField.setText(new BigDecimal(totalAmountDueTextField.getText()). setScale(2, RoundingMode.FLOOR));

Sumit Bhatt
  • 718
  • 4
  • 19