【问题标题】:Javafx double variable with two decimal placesJavafx 双变量,小数点后两位
【发布时间】:2018-06-04 00:59:15
【问题描述】:

我有一个双倍的变量名“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();

提前致谢。

【问题讨论】:

    标签: java double precision decimalformat


    【解决方案1】:

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

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

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

    当您需要将数字显示为 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());
                }
            })
    

    ;

    【讨论】:

    • 那么,有没有办法将其保留为数值而不是字符串以具有尾随零?因为,我在表格列中使用了这个值,我不想继续玩这个值。我想要的只是以双精度(包括尾随零)存储价格值,并将其以数字格式存储在表格列中。
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 2018-10-06
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多