简体   繁体   English

如何使用 System.out.printf() 将数字的 output 显示到小数点后两位?

[英]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.我正在为 class 创建我的第一个 java 程序。 The purpose of the program is to calculate interest for deposit for year one and year two.该程序的目的是计算第一年和第二年的deposit interest My issue comes when the code outputs the final totals.当代码输出最终总数时,我的问题就出现了。 The last two lines are supposed to use System.out.printf() .最后两行应该使用System.out.printf() I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i' .我不断收到错误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();
}

The % symbol is used in a printf string for 'put a variable here'. %符号在 printf 字符串中用于“在此处放置变量”。

That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here".当您编写4.9% interest rate时,这是有问题的,因为 java 认为% i是您在说:“这里有一个变量”。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM