How can I format 2 decimal places in monetary amount?

Viewed 502

i was assigned a question to design a java program to calculate the price of a pizza, this is what I tried:

        String diameter;
        diameter = this.txtInput.getText();
        
        // variable declaration and intialize for "labourCost" and "storeCost"
        double labourCost, storeCost;
        labourCost = 1;
        storeCost = 1.5;       
        
        // convert the value inputted from a string to double
        double dblDiameter= Double.parseDouble(diameter);
        
        // variable declarationa and intialize the value for the variable "cost"
        double cost = (labourCost + storeCost + (0.5 * dblDiameter));
        
        // print the output
        this.lblOutput.setText("The cost of the pizza is $" + cost);

The output I got is $7.5, my question is how can I format it so it will display $7.50? thank you.

3 Answers

You can try with DecimalFormat:

DecimalFormat decimalFormat = new DecimalFormat("#.00");

And then:

this.lblOutput.setText("The cost of the pizza is $" + decimalFormat.format(cost));

Or you can use String.format:

this.lblOutput.setText("The cost of the pizza is $" + String.format("%.2f", cost));

I recommend you use BigDecimal#setScale as shown below:

this.lblOutput.setText("The cost of the pizza is $" + BigDecimal.valueOf(cost).setScale(2, RoundingMode.CEILING));

Alternatively, you can use String#format as shown below:

this.lblOutput.setText("The cost of the pizza is $" + String.format("%.2f", cost));

Another option is by using DecimalFormat#format as shown below:

NumberFormat formatter = new DecimalFormat("#.00");
this.lblOutput.setText("The cost of the pizza is $" + formatter.format(cost));

I am looking at different ways to use currency in java, I have the same problem. So it loosk like that the MonetaryAmount object does not handle formatting, and you have to use formatting objects.

Related