Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - How to use System.out.printf() to display output of number to only two decimal places?

I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?

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

    System.out.println("Hello World!");

    //declares variables
    double interest = 0;
    double balance = 0;
    double deposit = 0;
    double secondYearBalance = 0;
    double secondYearInterest = 0;

    //displays welcome message
    System.out.println("Welcome to George's Interest Calculator");

    //prompts user for input
    System.out.println("Please enter your initial deposit:");
    deposit = keyboard.nextInt();

    //Finds outs interest interest earned on deposit
    interest = deposit * TAXRATE;

    //Finds out the amount of the balance
    balance = deposit + interest;

    //finds out second year balance
    secondYearInterest = balance * TAXRATE;
    secondYearBalance = secondYearInterest + balance;

    //Outputs totals
    System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
    System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);

    System.out.println();
}
question from:https://stackoverflow.com/questions/65908521/how-to-use-system-out-printf-to-display-output-of-number-to-only-two-decimal-p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The % symbol is used in a printf string for 'put a variable here'.

That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:

System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...