TableColumn 中的 JavaFX 格式双精度

Pan*_*010 2 java formatting javafx tableview

TableColumn<Product, Double> priceCol = new TableColumn<Product,Double>("Price");
priceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));
Run Code Online (Sandbox Code Playgroud)

如何格式化此列中的双精度数以保留 2 位小数(因为它们是价格列)?默认情况下,它们仅显示 1 位小数。

Jam*_*s_D 7

使用生成单元格的单元格工厂,这些单元格使用货币格式化程序来格式化显示的文本。这意味着价格将被格式化为当前区域设置中的货币(即使用当地货币符号和小数位数的适当规则等)。

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
priceCol.setCellFactory(tc -> new TableCell<Product, Double>() {

    @Override
    protected void updateItem(Double price, boolean empty) {
        super.updateItem(price, empty);
        if (empty) {
            setText(null);
        } else {
            setText(currencyFormat.format(price));
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,这是您已经使用的之外的。cellValueFactory确定cellValueFactory单元格中显示的值;确定定义如何cellFactory显示它的单元格。