我想在用户实时输入数字的同时,将价格格式化为100,000,000,有什么办法吗?
你可以很容易地尝试使用小数格式化器。
DecimalFormat myFormat = new DecimalFormat("###,##0.00");
myFormat.format(yourValue);
如果你只想让小数点的数字在呈现的时候才出现,就用这样的模式吧 "###,###.##"
.
编辑
如果你想在用户输入时更新,你应该使用 onAction
方法的JavaFX。
例如,你可以这样做。
如果这是你的TextField(你甚至可以在控制器中使用它)
<TextField fx:id="money" onKeyTyped="#updateText">
</TextField>
控制器
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());
}
}
希望是你要找的。
这里有一个简单的解决方案。
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);
}
}
});