我有一个 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()
将简单地返回原始 double
值12d
.
此外,使用 .##
表示该值将四舍五入到小数点后两位,但如果您的值少于小数点后两位,则不会保留小数点后两位。
当您需要将数字显示为 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/