Java - 即使在零中也始终保留两个小数位

use*_*874 5 java decimalformat

我试图保留两个小数位,即使那时数字为零,使用DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.00");

m_interest   = Double.valueOf(df.format(m_principal * m_interestRate));
m_newBalance = Double.valueOf(df.format(m_principal + m_interest - m_payment));
m_principal  = Double.valueOf(df.format(m_newBalance));
Run Code Online (Sandbox Code Playgroud)

但是对于某些值,这会给出两个小数位,而对于其他值则不会.我怎样才能解决这个问题?

Mic*_*ski 6

这是因为你正在使用Double.valueOfDecimalFormat,它是转换格式的数字回到了一倍,从而消除拖尾0.

为了解决这个问题,只使用DecimalFormat,当你显示的值.

如果您需要m_interest计算,请将其保留为常规double.

然后在显示时,使用:

System.out.print(df.format(m_interest));
Run Code Online (Sandbox Code Playgroud)

例:

DecimalFormat df = new DecimalFormat("#.00");
double m_interest = 1000;
System.out.print(df.format(m_interest)); // prints 1000.00
Run Code Online (Sandbox Code Playgroud)


Hov*_*els 5

DecimalFormatNumberFormat 应该可以正常工作。货币实例可以工作得更好

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Foo {
   public static void main(String[] args) {
      DecimalFormat df = new DecimalFormat("#0.00");

      NumberFormat nf = NumberFormat.getInstance();
      nf.setMinimumFractionDigits(2);
      nf.setMaximumFractionDigits(2);

      NumberFormat cf = NumberFormat.getCurrencyInstance();

      System.out.printf("0 with df is: %s%n", df.format(0));
      System.out.printf("0 with nf is: %s%n", nf.format(0));
      System.out.printf("0 with cf is: %s%n", cf.format(0));
      System.out.println();
      System.out.printf("12345678.3843 with df is: %s%n",
            df.format(12345678.3843));
      System.out.printf("12345678.3843 with nf is: %s%n",
            nf.format(12345678.3843));
      System.out.printf("12345678.3843 with cf is: %s%n",
            cf.format(12345678.3843));
   }
}
Run Code Online (Sandbox Code Playgroud)

这将输出:

0 with df is: 0.00
0 with nf is: 0.00
0 with cf is: $0.00

12345678.3843 with df is: 12345678.38
12345678.3843 with nf is: 12,345,678.38
12345678.3843 with cf is: $12,345,678.38
Run Code Online (Sandbox Code Playgroud)