Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

java - Showing DoubleProperty up to two decimal places in TableView

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

A rough layout looks like this:

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)
    }
}

And I fill the column with:

   ...
   myCol.setCellValueFactory(cellData ->cellData.getValue().getPropertyMyDouble().asObject());
   ...

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.

What I tried doing is something like this:

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

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.

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;

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...