1

I do get the price from the user but I want to filter the digits and puts, in each 3 digits like 123,123,123.

txtPrice.textProperty().addListener((observable, oldValue, newValue) -> {
   if (!newValue.matches("\\d*")){
       txtPrice.setText(newValue.replaceAll("[^\\d]",""));
   }
});
Jonah
  • 69
  • 2
  • 11

2 Answers2

5

To format number as you specified, you may try this:

// Eg: format "123123123" as "123,123,123"
if (newValue.matches("\\d*")) {
    DecimalFormat formatter = new DecimalFormat("#,###");
    String newValueStr = formatter.format(Double.parseDouble(newValue));

    txtPrice.setText(newValueStr);
}

Hope this help, good luck!

Shuwn Yuan Tee
  • 5,578
  • 6
  • 28
  • 42
0

Try this:

textFieldUsername.setOnKeyTyped(event -> {
    String typedCharacter = event.getCharacter();
    event.consume();

    if (typedCharacter.matches("\\d*")) {
        String currentText = textFieldUsername.getText().replaceAll("\\.", "").replace(",", "");
        long longVal = Long.parseLong(currentText.concat(typedCharacter));
        textFieldUsername.setText(new DecimalFormat("#,##0").format(longVal));
    }
});
E. Betanzos
  • 1,312
  • 1
  • 9
  • 14
  • 1
    no, don't do the formatting in a key handler (will miss copied or otherwise updated text) plus don't do any manual formatting (will blow in different Locales) – kleopatra Feb 08 '18 at 10:53
  • this method works great but can we do it better? i did search about TextFormatter but i can't understand it i need to learn how to do this on my own so guys what should i learn and give me some good resources – Jonah Feb 08 '18 at 11:55