How to format text of TextField? JavaFX

梦想的初衷 提交于 2019-12-11 06:57:26

问题


For example, if I enter 32164578542324236.97325074, this number should be displayed in a TextField like 32,164,578,542,324,236.97325074. I tried to handle this, but unsuccessfully:

    inputField.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            BigDecimal bd = new BigDecimal(newValue);
            NumberFormat formatter = NumberFormat.getNumberInstance();             
            inputField.setText(formatter.format(newValue));
        }
    });

Maybe it would be better to use inputField.setTextFormatter(); but I'm not familiar with this method. Thanks in advance!


回答1:


Try :

BigDecimal bd = new BigDecimal(newValue);
DecimalFormat formatter  = new DecimalFormat(",###");// seperate them by ',' while digits after '.' are excluded
String newestValue = formatter.format(bd)+newValue.substring(newValue.indexOf("."));// concatenate with the digits after '.'
inputField.setText(newestValue);


来源:https://stackoverflow.com/questions/31382250/how-to-format-text-of-textfield-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!