Javafx double 变量,具有两位小数

标签 java double precision decimalformat

我有一个 double 变量名称“unitPrice”。 如果单价的值 = 12.23; 可以,并且给出带有两位小数的 double 。

但是如果该值为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();

提前致谢。

最佳答案

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

因此,df2.format(unitPrice)将评估为 String值(value)"12.00"new Double("12.00")将创建一个Double值为 12d ,和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());
            }
        })

;

关于Javafx double 变量,具有两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672302/

相关文章:

使用管道 '|'使用多个分隔符分割Java字符串

java - 从 Excel 文件 (xlsx) 创建模板文件 (xltx)

MATLAB 强制 num2str 格式化

c - Angelscript错误的类型转换

haskell - 对无限级数的有限前缀求和

java - 我会在这里同步什么?

java - 生成 EAR 时未添加项目实用程序 Jar

c - 如何将 4 个 modbus 寄存器(每个 16 位)转换为 C 中的双 float ?

c# - Double 除以零返回除以零错误

c++ - 将 double 转换为数组的单个数字