问题描述
我试图保留两个小数位,即使这些数字为零,使用 DecimalFormatter
:
I am trying to keep two decimal places, even if then numbers are zeroes, using 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));
但是对于某些值,这会给出两个小数位,而对于其他值,它不会。我该如何解决这个问题?
However for some values this gives two decimal places, and for others it doesnt. How can i fix this?
推荐答案
这是因为你使用的是 Double.valueOf
在 DecimalFormat
上,它将格式化的数字转换回double,因此消除了尾随的0。
It is because you are using Double.valueOf
on the DecimalFormat
and it is converting the formatted number back to a double, therefore eliminating the trailing 0s.
要解决此问题,请在显示时使用 DecimalFormat
值。
To fix this, only use the DecimalFormat
when you are displaying the value.
如果您需要 m_interest
计算,请将其保留为常规双
。
If you need m_interest
calculations, keep it as a regular 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
这篇关于Java - 即使在零中也始终保留两个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!