Search code examples
javaiodecimal

Displaying an output decimal with 2 places in java


I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.

I get an exception in thread "main"

Java.util.illegalformatconversionexception  f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)

Here is my code:

import java.util.Scanner;
public class Cars
{

  public static void main(String [] args)
  {
    Scanner input = new Scanner(System.in);

    int carYear, currentYear, carAge;

    double costOfCar, salesTaxRate;
    double totalCost;

    String carModel;
    System.out.println("Please enter your favorite car model.");
        carModel = input.nextLine();
    System.out.println("Please enter the  year of the car");
        carYear = input.nextInt();
    System.out.println("Please enter the current year.");
        currentYear = input.nextInt();
        carAge = currentYear - carYear;
    System.out.println("How much does the car cost?");
        costOfCar = input.nextDouble();
    System.out.println("What is the sales tax rate?");
        salesTaxRate = input.nextDouble();
        totalCost = (costOfCar + (costOfCar * salesTaxRate));
    System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars."); 

    }
}

I'm not exactly sure what's causing the issue.


Solution

  • Try:

    System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
    

    Or the more readable:

    System.out.printf("The model of your favorite car is %s," +
                      " the car is %d years old," +
                      " the total of the car is %.2f dollars.",
                      carModel, carAge, totalCost);