JavaFx TextField 货币格式过滤器

JavaFx TextField Currency format filter

我确实从用户那里得到了价格,但我想过滤数字和看跌期权,每 3 位数字,如 123,123,123。

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

要按照您指定的格式格式化数字,您可以试试这个:

// 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);
}

希望对您有所帮助,祝您好运!

试试这个:

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));
    }
});