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
887 views
in Technique[技术] by (71.8m points)

java - JavaFX format double in TableColumn

TableColumn<Product, Double> priceCol = new TableColumn<Product,Double>("Price");
priceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));

How do I format the doubles in this column to have 2 decimal places(Because they are the column for price)?By default they only show 1 decimal place.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Use a cell factory that generates cells that use a currency formatter to format the text that is displayed. This means the price will be formatted as a currency in the current locale (i.e. using the local currency symbol and appropriate rules for number of decimal places, etc.).

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
priceCol.setCellFactory(tc -> new TableCell<Product, Double>() {

    @Override
    protected void updateItem(Double price, boolean empty) {
        super.updateItem(price, empty);
        if (empty) {
            setText(null);
        } else {
            setText(currencyFormat.format(price));
        }
    }
});

Note this is in addition to the cellValueFactory you are already using. The cellValueFactory determines the value that is displayed in a cell; the cellFactory determines the cell that defines how to display it.


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

...