在TableView中显示DoubleProperty最多两个小数位 [英] Showing DoubleProperty up to two decimal places in TableView

查看:122
本文介绍了在TableView中显示DoubleProperty最多两个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题,直到第二个小数点才显示doubleProperty。

I'm having a problem showing a doubleProperty up until the second decimal.

粗略的布局如下所示:

public static void main(String[] args) {
    private TableView<myType> myTable;
    private TableColumn<myType, Double> 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 包含
多个小数的数字。我只想要小数点后两位。

Now my problem is this: If I leave the setMyDouble method the way it is, myCol is full of numbers with lots of decimals. I only want up to the second decimal.

我尝试做的是这样的:

public void setMyDouble(double d) {
        BigDecimal bd = new SimpleDecimalFormat("#.00")
        myDouble.set(Double.parseDouble(bd.format(d));
    }

现在这适用于删除第二个小数后的数字,但问题是如果我有一些
像12.00,因为我需要在最后转换为一个双倍(因为 .set()需要一倍)它变成12.00
到12.0。但是,我需要一直保留两位小数。

Now this works in removing digits after the second decimal, but the problem is that if I have something like 12.00, because I need to convert to a double at the end (Since .set() takes a double) it turns 12.00 into a 12.0. However, I need to keep two decimal places all the time.

有没有办法保留 myDouble 作为 DoubleProperty (我这样做是因为它使更改后的表自动更新表)
但是显示数据在#。##格式?

Is there any way to keep myDouble as a DoubleProperty (I'm doing this because it makes updating the table automatically after changes much easier) but present the data as in the "#.##" format?

我在考虑做一些像添加实例变量的事情:

I was thinking maybe doing something like adding an instance variable:

StringProperty myDoublePresent;

只需 myDouble 然后转过来到一个字符串,然后出现在#。##格式。

which would just take myDouble and turn it into a string and then present in the "#.##" format.

但我更喜欢方法,我可以直接使用 DoubleProperty。

But I'd prefer a method where I can work directly with the DoubleProperty.

推荐答案

尝试

myCol.setCellValueFactory(cellData ->
     Bindings.format("%.2f", cellData.getValue().getPropertyMyDouble()));

这篇关于在TableView中显示DoubleProperty最多两个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆