how can i format price to 2 decimal places [duplicate]

How can i format the price to 2 decimal places and how can i when a user enter invalid number print on the screen invalid selection only in my code now its printing invalid selection but it is also printing after it -1 i want it without the -1
can someone help me with this I'm fairly new to java

import java.util.Scanner;
import java.util.logging.Formatter;

public class CoffeeServingV1 {
    public static class CoffeeServing {
        private double size;
        
        public CoffeeServing() {
            this(2);
            return;
        }
        
        public CoffeeServing(int size) { 
            this.size = size;
            return;
        }
    
        public double getSize() {
            return size;
        }
                    
        public void setSize(double size) {
            this.size = size;
            return;
        }
                
        public double calculatePrice() {
            double price;

            if (size == 1)
                price = 3.25;
            else if (size == 2)
                price = 4.50;
            else if (size == 3)
                price = 6.00;
            else
                price = -1;}
            
            return price;
        }
                
        public String createReport() {
            String report;
            double price;
            price = calculatePrice();
            
            if (size == 1)
                report = "small coffee $";
            else if (size == 2)
                report = "medium coffee $";
            else if (size == 3)
                report = "large coffee $";
            else
                report = "invalid size selected $";
            
            report = report + price;
                
            return report;
        }
    }
    
    public static void main(String[] args) {
        double coffeeSize;
        String report;
        CoffeeServing coffee = new CoffeeServing();
            
        System.out.println("Welcome to Make Coffee Version 1");
        System.out.println("enter coffee size: ");
        System.out.println("1 for Small");
        System.out.println("2 for Medium");
        System.out.println("3 for Large");
            
        Scanner keyboard = new Scanner(System.in);
        coffeeSize = keyboard.nextInt();
        coffee.setSize(coffeeSize);
        report = coffee.createReport();
        
        System.out.println(report);
    }
}


Read more here: https://stackoverflow.com/questions/68488082/how-can-i-format-price-to-2-decimal-places

Content Attribution

This content was originally published by user16218933 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: