【问题标题】:JavaFX format double in TableColumnTableColumn 中的 JavaFX 格式加倍
【发布时间】:2018-07-21 20:02:05
【问题描述】:
TableColumn<Product, Double> priceCol = new TableColumn<Product,Double>("Price");
priceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));

如何将此列中的双精度设置为具有 2 个小数位(因为它们是价格列)?默认情况下它们只显示 1 个小数位。

【问题讨论】:

    标签: java javafx formatting tableview


    【解决方案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));
            }
        }
    });
    

    注意这是除了您已经在使用的cellValueFactorycellValueFactory 确定单元格中显示的值; cellFactory 确定定义如何显示它的单元格。

    【讨论】:

    • 也对我有用,我也可以对其进行编辑以使用十进制格式。
    • 我在我的项目中尝试了相同的解决方案。但我收到“无法将给定的对象格式化为数字”。我传递了双重价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2020-05-07
    • 2013-11-25
    • 1970-01-01
    • 2014-05-09
    • 2022-01-20
    • 2017-11-25
    相关资源
    最近更新 更多