在TableView中显示DoubleProperty最多两个小数位
我有一个问题显示doubleProperty直到第二个小数。
粗略的布局看起来像这样:
public static void main(String[] args) { private TableView myTable; private TableColumn myCol; public class myObject { ..... DoubleProperty myDouble; .... public doubleProperty getPropertyMyDouble() { return myDouble; } public void setMyDouble(double d) { myDouble.set(d) } }
我在列中填写:
... myCol.setCellValueFactory(cellData ->cellData.getValue().getPropertyMyDouble().asObject()); ...
现在我的问题是这样的:如果我按照它的方式离开setMyDouble
方法, myCol
充满了带有大量小数的数字。 我只想要小二进制。
我尝试做的是这样的:
public void setMyDouble(double d) { BigDecimal bd = new SimpleDecimalFormat("#.00") myDouble.set(Double.parseDouble(bd.format(d)); }
现在这适用于删除第二个小数后的数字,但问题是如果我有类似12.00的东西,因为我需要在结尾处转换为double(因为.set()
需要一个双倍)它将12.00转换为12.0 。 但是,我需要一直保留两位小数。
是否有任何方法可以将myDouble
保持为DoubleProperty
(我这样做是因为它更容易在更改后自动更新表)但是以"#.##"
格式显示数据?
我在考虑做一些像添加实例变量的事情:
StringProperty myDoublePresent;
这将只需要myDouble
并将其转换为字符串,然后以"#.##"
格式显示。
但我更喜欢一种方法,我可以直接使用DoubleProperty.
尝试
myCol.setCellValueFactory(cellData -> Bindings.format("%.2f", cellData.getValue().getPropertyMyDouble()));
遵循James_D在接受的答案中的建议是允许格式化任何列的通用解决方案。
public class DecimalColumnFactory implements Callback, TableCell> { private DecimalFormat format; public DecimalColumnFactory(DecimalFormat format) { super(); this.format = format; } @Override public TableCell call(TableColumn param) { return new TableCell() { @Override protected void updateItem(T item, boolean empty) { if (!empty && item != null) { setText(format.format(item.doubleValue())); } else { setText(""); } } }; } }
这可以用来
theColumn.setCellFactory(new DecimalColumnFactory<>(new DecimalFormat("0.00")));