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

本文讲述了如何使用DecimalFormatter保持两位小数一致,尤其是在处理零值时。作者揭示了Double.valueOf导致小数点后零丢失的问题,并给出了将计算和显示分开的解决方案,以及示例代码。
摘要由CSDN通过智能技术生成

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?

解决方案

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.

To fix this, only use the DecimalFormat when you are displaying the value.

If you need m_interest calculations, keep it as a regular double.

Then when displaying, use:

System.out.print(df.format(m_interest));

Example:

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

double m_interest = 1000;

System.out.print(df.format(m_interest)); // prints 1000.00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值