简体   繁体   中英

JavaFX Tableview limit the number of digits after point

我有一个基于tableview的表,它由double值填充我收到了trougth API,我想在点之后只显示3位数。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM