【问题标题】:Java - toString Formatting (Formatting Doubles)Java - toString 格式化(格式化双精度)
【发布时间】:2015-07-21 20:48:45
【问题描述】:

我正在进行的项目需要使用 toString 方法打印银行账户余额。我不允许向我当前的程序添加任何方法,但我需要将 myBalance 变量格式化为一个双精度数,该双精度数可以保留两位小数,而不是一位。在这个特定的例子中,我的程序应该打印 8.03,但它打印的是 8.0。

这是我的 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 变量。谢谢!

【问题讨论】:

    标签: java formatting tostring


    【解决方案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 获得特定于平台的换行符,如果我想将字符串写入文件,这尤其有用。请注意,String.format(...) 以及 System.out.printf(...) 和类似方法在后台使用 java.util.Formatter,因此这也适用于它们。

    【讨论】:

    • 我明白了!我不知道你可以这样写。非常感谢先生/女士。另外,我爱你的用户名。
    • 你的意思是\n 你有%n 吗?
    • @khelwood:不,我绝对是指%n 而不是\n。当使用 java.util.Formatter (这是 String.format(...) 使用的)时,您应该避免使用 \n 并优先使用 %n
    • 我没有意识到这一点。干杯。
    • @khelwood:没问题。请注意,它允许根据this question 使用特定于平台的新行。请注意,printf 在幕后也使用了java.util.Formatter
    【解决方案2】:

    使用 String.format()

    例子:

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

    输出: 8.03

    【讨论】:

    • link 的可能重复项
    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多