JavaFX Tableview limit the number of digits after point


Question

I have a table based on tableview , it is populated by double values I recieve trougth API , and I want to display only 3 digits after point.

1
1
6/26/2014 3:26:51 PM

Accepted Answer

Use a StringConverter to get the desired format, and install it, using a TextFieldTableCell like this:

    threeDigitColumn.setCellFactory(TextFieldTableCell.<RowModel, Double>forTableColumn(new StringConverter<Double>() {
        private final NumberFormat nf = NumberFormat.getNumberInstance();

        {
             nf.setMaximumFractionDigits(3);
             nf.setMinimumFractionDigits(3);
        }

        @Override public String toString(final Double value) {
            return nf.format(value);
        }

        @Override public Double fromString(final String s) {
            // Don't need this, unless table is editable, see DoubleStringConverter if needed
            return null; 
        }
    }));
2
6/26/2014 5:28:59 PM

Use a custom cell factory on the table columns:

Callback<TableColumn<S, Double>, TableCell<S, Double>> cellFactory = new Callback<TableColumn<S, Double>, TableCell<S, Double>() {
    @Override
    public TableCell<S, Double> call(TableColumn<S, Double> col) {
        return new TableCell<S, Double>() {
            @Override
            public void updateItem(Double value, boolean empty) {
                super.updateItem(value, empty) ;
                if (value==null) {
                    setText(null);
                } else {
                    setText(String.format("%.3f", value.doubleValue()));
                }
            }
        };
    }
}
tableCol.setCellFactory(cellFactory);

(where you replace S with the data type for the table).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon