gpt4 book ai didi

TableColumn 中的 JavaFX 格式 double

转载 作者:行者123 更新时间:2023-12-02 11:38:42 24 4
gpt4 key购买 nike

TableColumn<Product, Double> priceCol = new TableColumn<Product,Double>("Price");
priceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));

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

最佳答案

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

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

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

关于TableColumn 中的 JavaFX 格式 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com