我试图保留两个小数位,即使后面的数字是零,使用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));
但是对于某些值,这会给出两个小数位,而对于其他值则不会。我该如何解决这个问题?
答案 0 :(得分:6)
这是因为您在Double.valueOf
上使用DecimalFormat
并且它正在将格式化的数字转换回double,因此消除了尾随的0。
要解决此问题,请在显示值时使用DecimalFormat
。
如果您需要m_interest
计算,请将其保留为常规double
。
然后在显示时,使用:
System.out.print(df.format(m_interest));
示例:
DecimalFormat df = new DecimalFormat("#.00");
double m_interest = 1000;
System.out.print(df.format(m_interest)); // prints 1000.00
答案 1 :(得分:4)
DecimalFormat 和 NumberFormat应该可以正常工作。货币实例可以甚至更好:
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));
}
}
这将输出:
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
答案 2 :(得分:2)
请改用BigDecimal,它支持您寻找的格式化方法。
答案 3 :(得分:0)
m_interest = Double.valueOf(String.format("%.2f", sum));
答案 4 :(得分:-1)
为什么不简单地Math.round(值* 100)/ 100.0?