Reputation: 477
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.
Upvotes: 1
Views: 5980
Reputation: 36743
Following James_D suggestion in the accepted answer here is the general purpose solution allowing formatting of any column.
public class DecimalColumnFactory<S, T extends Number> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
private DecimalFormat format;
public DecimalColumnFactory(DecimalFormat format) {
super();
this.format = format;
}
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableCell<S, T>() {
@Override
protected void updateItem(T item, boolean empty) {
if (!empty && item != null) {
setText(format.format(item.doubleValue()));
} else {
setText("");
}
}
};
}
}
this can be used by
theColumn.setCellFactory(new DecimalColumnFactory<>(new DecimalFormat("0.00")));
Upvotes: 3
Reputation: 49215
Try
myCol.setCellValueFactory(cellData ->
Bindings.format("%.2f", cellData.getValue().getPropertyMyDouble()));
Upvotes: 6