double 变量不存储您使用 DecimalFormat 指定的精度。 DecimalFormat 对象用于将数字转换为您指定格式的String(因为您调用了format())。
因此,df2.format(unitPrice) 将评估为 String 的值 "12.00"。 new Double("12.00") 将创建一个值为12d 的Double,而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());
}
})
;