0

I need to display 2 decimal point but I don't get it how to do It.

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number

import java.text.DecimalFormat;
import java.util.Scanner;
public class ShoppingOrders {
    public static void main(String[] args) {
        double itemPrice, shippingFeeRate, shippingFee,totalCost;
        String nameItem;
        Scanner myScanner= new Scanner (System.in);
        DecimalFormat df = new DecimalFormat("#.00");
        
        nameItem = myScanner.nextLine();
        itemPrice = myScanner.nextDouble();
        shippingFeeRate = myScanner.nextDouble();
        
        shippingFee =shippingFeeRate*itemPrice;
        totalCost = shippingFee+itemPrice;
        
        System.out.println ("Costs for "+nameItem);
        System.out.println (df.format("Item Price: $" +itemPrice));
        System.out.println (df.format("Shipping Fee: $"+ shippingFee));
        System.out.println (df.format("Total Cost: $"+totalCost));
    }
}
0

2 Answers 2

1

You are using DecimalFormat.format(...) incorrectly. You don't pass it a String. You pass it an object that represents a number. (Or a primitive number type which will be boxed to an object that represents a number.)

For example:

df.format(itemPrice)    // itemPrice will be boxed to a Double

So if you want to include a message in the output, you might do this:

System.out.println("Item Price: $" + df.format(itemPrice));

Alternatively, you could use String.format(...) and specify the number of digits after the decimal point in the format specifier.

Sign up to request clarification or add additional context in comments.

Comments

0

DecimalFormat.format(...) is for formatting a number. In your case, you added a String to the double, which turns it into a String, which DecimalFormat.format(...) doesn't support. Instead, use:

import java.text.DecimalFormat;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
    double itemPrice, shippingFeeRate, shippingFee,totalCost;
    String nameItem;
    Scanner myScanner= new Scanner (System.in);
    DecimalFormat df = new DecimalFormat("#.00");
    
    nameItem = myScanner.nextLine();
    itemPrice = myScanner.nextDouble();
    shippingFeeRate = myScanner.nextDouble();
    
    shippingFee =shippingFeeRate*itemPrice;
    totalCost = shippingFee+itemPrice;
    
    System.out.println ("Costs for "+nameItem);
    System.out.println ("Item Price: $" +df.format(itemPrice));
    System.out.println ("Shipping Fee: $"+ df.format(shippingFee));
    System.out.println ("Total Cost: $"+df.format(totalCost));
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.