首页 > 解决方案 > Javafx 双变量,小数点后两位

问题描述

我有一个双倍的变量名称“unitPrice”。如果 unitprice 的值 = 12.23;没关系,并给出带两位小数的双精度。

但是,如果值为 unitPrice = 12.50; 或单位价格 = 12.00;

它给出“12.5”和“12.0”有没有办法让这个“12.50”和“12.00”?

这是我的代码。

unitPrice = 12.00;
        DecimalFormat df2 = new DecimalFormat(".##");

    double formatDecimal = new Double(df2.format(unitPrice)).doubleValue();

提前致谢。

标签: javadoubleprecisiondecimalformat

解决方案


double变量不存储您使用 指定的精度DecimalFormat。该DecimalFormat对象用于将数字转换为String您指定格式的 a(因为您调用了format())。

因此,df2.format(unitPrice)将评估成一个String价值"12.00"new Double("12.00")将创建一个Double值为 的12ddoubleValue()并将简单地返回原始double12d

此外, using.##意味着该值将四舍五入到小数点后 2 位,但如果您的值少于小数点后 2 位,则不会保留 2 位小数。

当您需要将数字显示为String.

double price = 12;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(price);
System.out.println(df.format(price));

输出:

12
12.00

编辑

假设您使用的是 JavaFX(因为您的问题最初有javafx标签)。

一种方法是使用setCellFactory()(参见this)。

另一种方法是使用setCellValueFactory().

@FXML private TableColumn<Foo, String> column;

column.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Foo, String>, ObservableValue<String>>() {
            DecimalFormat df = new DecimalFormat("#.00");

            @Override
            public ObservableValue<String> call(CellDataFeatures<Foo, String> param) {
                return Bindings.createStringBinding(() -> {
                           return df.format(param.getValue().getPrice());
                       }, param.getValue().priceProperty());
            }
        })

;


推荐阅读