正确格式化

时间:2015-01-15 09:16:38

标签: java formatting

我让程序正常工作我只需要帮助切断多余的数字,我在使用Java打印时不太熟练使用printf语句。当我运行它时,我得到输出像1225.043这是我的拥有:

import java.util.Scanner;

public class Comparison {

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

        float amount;
        double principal = 1000.00;
        double rate;


        System.out.println("Enter interest rate");
        rate = keyboard.nextDouble();

        System.out.println("Year" +"     "+ "Amount on deposit");

        for(int year = 1; year <= 10; ++year)
        {
            amount = (float) (principal * Math.pow(1.0 + rate, year));

            System.out.println(year+ "       "+ amount);
            System.out.println();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试

System.out.printf("%2d       %.2f%n", year, amount);

<强>输出:

Enter interest rate
0.1
Year     Amount on deposit
 1       1100.00
 2       1210.00
 3       1331.00
 4       1464.10
 5       1610.51
 6       1771.56
 7       1948.72
 8       2143.59
 9       2357.95
10       2593.74