2012-10-28 307 views
2

System.printf(“%。2f”,currentBalance)工作正常,但问题出现在句子后面的舍入数字。把代码放到你的eclipse程序中并运行它,你可以看到一些肯定是错误的。如果有人能帮助它,将不胜感激。尝试在java中舍入到小数点后两位数

public class BankCompound { 


public static void main (String[] args) { 
    compound (0.5, 1500, 1); 
} 

public static double compound (double interestRate, double currentBalance, int year) { 

    for (; year <= 9 ; year ++) { 

    System.out.println ("At year " + year + ", your total amount of money is "); 
    System.out.printf("%.2f", currentBalance); 
    currentBalance = currentBalance + (currentBalance * interestRate); 
    } 
    System.out.println ("Your final balance after 10 years is " + currentBalance); 
    return currentBalance; 
} 

}

回答

2

请试试这个

import java.text.DecimalFormat; 



public class Visitor { 


    public static void main (String[] args) { 
     compound (0.5, 1500, 1); 
    } 

    public static double compound (double interestRate, double currentBalance, int year) { 

     for (; year <= 9 ; year ++) { 

     System.out.println ("At year " + year + ", your total amount of money is "+Double.parseDouble(new DecimalFormat("#.##").format(currentBalance))); 


     currentBalance = currentBalance + (currentBalance * interestRate); 
     } 
     System.out.println ("Your final balance after 10 years is " + currentBalance); 
     return currentBalance; 
    } 
} 
+1

DecimalFormat是要走的路。如果您反复使用相同的格式,请将DecimalFormat设置为静态最终值并重新使用它以提高效率。 – AWT

1

System.out.println(),顾名思义

的行为就像先调用print(String),然后println()

使用System.out.print()并在打印当前余额后放入换行符。

System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f", currentBalance); 
System.out.println(); 

// or 
System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f\n", currentBalance); 
0

System.out.printf( “在一年%d,您的资金总量%.2f \ n”,今年,currentBalance);

0

故障呼叫是打印给定内容后追加新行的第一个System.out.println()。

有两种解决方案 -

方法-1:

System.out.print("At year " + year + ", your total amount of money is "); 
System.out.printf("%.2f\n", currentBalance); 

方法-2:[用的println使用的String.format()()]

System.out.println ("At year " + year + ", your total amount of money is " 
             + String.format("%.2f", currentBalance)); 

两者都将产生相同的结果。即使是第二个更具可读性。

输出:

在今年1,您的资金总量为1500.00

在今年2,你的资金总量为2250.00

在今年3,你的资金总量3375.00所属

在今年4,你的资金总量为5062.50

在今年5,你的资金总额为7593.75

在今年6,你的资金总额为11390.63

在今年7,你的资金总额为17085.94

在今年8,你的资金总额为25628.91

在今年9,你的资金总额为38443.36

经过10年的最后余额为57665.0390625

的String.format返回formatte d字符串。 System.out中。printf还在system.out(控制台)上打印格式化的字符串。

按照您的需求使用它们。

相关问题