2015-07-21 226 views
0

我正在处理的项目需要使用toString方法打印银行帐户余额。我不允许在我的当前程序中添加任何方法,但是我需要将我的myBalance变量格式化为一个double而不是一个小数点后两位。在这个特定的例子中,我的程序应该打印8.03,但是打印8.0。Java - toString格式(格式化双精度)

这里是我的toString方法:

public String toString() 
    { 
     return"SavingsAccount[owner: " + myName + 
     ", balance: " + myBalance + 
     ", interest rate: " + myInterestRate + 
     ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
     ", service charges for this month: " + 
     myMonthlyServiceCharges + ", myStatusIsActive: " + 
     myStatusIsActive + "]"; 
    } 

我很新到Java还在,所以我想知道是否有落实%.2f到字符串的方式某处只能格式化myBalance变量。谢谢!

回答

1

使用String.format(...)此:

@Override 
public String toString() { 
    return "SavingsAccount[owner: " + myName + 
    ", balance: " + String.format("%.2f", myBalance) + 
    ", interest rate: " + String.format("%.2f", myInterestRate) + 
    ",\n number of withdrawals this month: " + myMonthlyWithdrawCount + 
    ", service charges for this month: " + 
    myMonthlyServiceCharges + ", myStatusIsActive: " + 
    myStatusIsActive + "]"; 
} 

或更简洁:

@Override 
public String toString() { 
    String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" + 
     "number of withdrawals this month: %d, service charges for this month: %.2f, " + 
     "myStatusIsActive: %s]", 
     myName, myBalance, myInterestRate, myMonthlyWithdrawCount, 
     myMonthlyServiceCharges, myStatusIsActive); 
    return result; 
} 

注意khelwood问起我使用的"%n"新线标记,而不是通常"\n"字符串。我使用%n,因为这将允许java.util.Formatter获取平台特定的新行,特别是在我想将字符串写入文件时非常有用。请注意0​​以及System.out.printf(...)和类似的方法在后台使用java.util.Formatter,所以这也适用于它们。

+0

我明白了!我不知道你可以这样写。非常感谢您的先生/女士。另外,我爱你的用户名。 – Trafton

+0

@Trafton:请参阅更新 –

+0

你的意思是'\ n'你有'%n'吗? – khelwood

0

使用的String.format()

例子:

Double value = 8.030989; 
System.out.println(String.format("%.2f", value)); 

输出: 8.03

+0

[link]的可能重复(http://stackoverflow.com/questions/4885254/string-format-to-format-double-in-java) – digidude