我确实从用户那里得到了价格,但我想过滤数字并放入每个3位数字,如123,123,123。
txtPrice.textProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue.matches("\\d*")){
txtPrice.setText(newValue.replaceAll("[^\\d]",""));
}
});
答案 0 :(得分:3)
要按指定格式编号,您可以尝试:
// 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);
}
希望这有帮助,祝你好运!
答案 1 :(得分:0)
试试这个:
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));
}
});