Java – 即使在零中也始终保留两个小数位
我试图保持两个小数位,即使当时的数字是零,使用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));
但是对于某些值,这会给出两个小数位,而对于其他值则不会。 我怎样才能解决这个问题?
这是因为您在DecimalFormat
上使用Double.valueOf
并且它将格式化的数字转换回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
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
请改用BigDecimal,它支持您寻求的格式化方法。
这个问题详细说明: 如何打印格式化的BigDecimal值?
m_interest = Double.valueOf(String.format("%.2f", sum));
你为什么不简单地Math.round(值* 100)/ 100.0?