java - 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();
提前致谢。
解决方案
double
变量不存储您使用 指定的精度DecimalFormat
。该DecimalFormat
对象用于将数字转换为String
您指定格式的 a(因为您调用了format()
)。
因此,df2.format(unitPrice)
将评估成一个String
价值"12.00"
。new Double("12.00")
将创建一个Double
值为 的12d
,doubleValue()
并将简单地返回原始double
值12d
。
此外, 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());
}
})
;
推荐阅读
- c# - XAML WPF 自定义控件库未在外部项目中显示嵌入图像
- java - 如何从firebase中的所有用户中检索特定的子数据
- javascript - Loadash对多列进行分组和求和
- php - 从选定的选项中获取 php 值
- python-3.x - 反向字符串递归函数循环
- javascript - 在 node.js 后端使用 gmail-send 时出现连接超时错误
- reactjs - 无法将调度连接到道具
- php - 从包含调用中包含的 PHP 传递变量
- function - 如何在 Clojure 中对字符串向量进行双重循环?
- .net - 在构造函数注入期间,Unity DI Container 是否可以识别正在构造的类型,并在解析引用时使用它?