-1

I want to format the price like 100,000,000 in textfield while users are entering number in it real time. Is there any way to do that?

kiarash
  • 77
  • 1
  • 5

2 Answers2

0

You can easily try with a decimal formatter:

DecimalFormat myFormat = new DecimalFormat("###,##0.00");
myFormat.format(yourValue);

If you want the decimal digits only if presents use the pattern "###,###.##".

EDIT

If you want to update while the user is typing, you should use the onAction methods of JavaFX.

For example you could do:

If this is your TextField (you can have it even in a controller)

<TextField fx:id="money" onKeyTyped="#updateText">
</TextField>

Controller

public class Controller {
    @FXML
    private TextField money;

    DecimalFormat myFormat = new DecimalFormat("###,##0.00");

    @FXML
    public void updateText(){
        this.money.setText(myFormat.format(Double.valueOf(money.getText())).toString());
    }
}

Hope it was what you were looking for.

-2

Here is a simple solution:

       priceField.textProperty().addListener((observable, oldValue, newValue) -> {
            if (!priceField.getText().equals("")) {
                DecimalFormat formatter = new DecimalFormat("###,###,###,###");
                if (newValue.matches("\\d*")) {
                    String newValueStr = formatter.format(Long.parseLong(newValue));
                    priceField.setText(newValueStr);
                } else {
                    newValue = newValue.replaceAll(",", "");
                    String newValueStr = formatter.format(Long.parseLong(newValue));
                    priceField.setText(newValueStr);
                }
            }

        });
kiarash
  • 77
  • 1
  • 5
  • 3
    no, using a listener to a property and changing its value on being notified is __fundamentally wrong__ ! Do use a TextFormatter instead, that class is designed for exactly your use-case – kleopatra May 02 '20 at 14:38