display two decimal places of a float in a TableView JavaFx

有些话、适合烂在心里 提交于 2020-03-25 12:32:15

问题


So basically I'm developing this Javafx app following the DAO pattern... and I want the floats to have that .00 end instead of .0 (to represents the balance.. money ) balance records in tableview with .0

here's how I initialized the tableview components

idC.setCellValueFactory(cellData -> cellData.getValue().idProperty().asObject());
balanceC.setCellValueFactory(cellData -> cellData.getValue().balanceProperty().asObject());
dateC.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
timeC.setCellValueFactory(cellData -> cellData.getValue().timeProperty());

回答1:


Use a cellFactory in addition to your cellValueFactory (I'm assuming balanceC is a TableColumn<T, Double> for some type T:

balanceC.setCellFactory(c -> new TableCell<>() {
    @Override
    protected void updateItem(Double balance, boolean empty) {
        super.updateItem(balance, empty);
        if (balance == null || empty) {
            setText(null);
        } else {
            setText(String.format("%.2f", balance.doubleValue());
        }
    }
});

You can add currency symbols and use more sophisticated formatting if needed.



来源:https://stackoverflow.com/questions/60746829/display-two-decimal-places-of-a-float-in-a-tableview-javafx

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