user1971804
user1971804

Reputation: 111

Javafx double variable with two decimal places

I have a variable name "unitPrice" which is double. if the value of unitprice = 12.23; it is ok and giving double precision with two decimal place.

However if the value is unitPrice = 12.50; or unitPrice = 12.00;

it is giving "12.5" and "12.0" is there any way to make this "12.50" and "12.00" ?

here is my code for that.

unitPrice = 12.00;
        DecimalFormat df2 = new DecimalFormat(".##");

    double formatDecimal = new Double(df2.format(unitPrice)).doubleValue();

Thanks in advance.

Upvotes: 0

Views: 4242

Answers (1)

Jai
Jai

Reputation: 8363

A double variable does not store the precision that you specify with DecimalFormat. The DecimalFormat object is used to convert a number into a String in the format that you specify (because you called format()).

Therefore, df2.format(unitPrice) will evaluate into a String of value "12.00". new Double("12.00") will create a Double with a value of 12d, and doubleValue() will simply return primitive double value 12d.

Furthermore, using .## means that the value will be rounded off to 2 decimal places, but if you have a value with less than 2 decimal places, it will not be made 2 decimal places.

Formatting is used when you need a number to be presented as a String.

double price = 12;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(price);
System.out.println(df.format(price));

Output:

12
12.00

Edit

Assuming you are using JavaFX (because your question originally had javafx tag).

One way is to use setCellFactory() (see this).

Another way is to use setCellValueFactory().

@FXML private TableColumn<Foo, String> column;

column.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Foo, String>, ObservableValue<String>>() {
            DecimalFormat df = new DecimalFormat("#.00");

            @Override
            public ObservableValue<String> call(CellDataFeatures<Foo, String> param) {
                return Bindings.createStringBinding(() -> {
                           return df.format(param.getValue().getPrice());
                       }, param.getValue().priceProperty());
            }
        })

;

Upvotes: 2

Related Questions