Search code examples
javafxtableviewtablecolumn

display two decimal places of a float in a TableView JavaFx


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());

Solution

  • 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.