JavaFx TextField 货币格式过滤器

Jon*_*nah 1 java javafx textfield

我确实从用户那里获得了价格,但我想过滤数字并输入,每 3 位数字如 123,123,123。

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

Shu*_*Tee 5

要按照您指定的格式设置数字,您可以尝试以下操作:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助,祝你好运!