Java - always keep two decimal places even in zero

2020-02-26 11:50发布

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?

5条回答
你好瞎i
2楼-- · 2020-02-26 11:55
m_interest = Double.valueOf(String.format("%.2f", sum));
查看更多
何必那么认真
3楼-- · 2020-02-26 11:57

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
查看更多
成全新的幸福
4楼-- · 2020-02-26 11:57

DecimalFormat and NumberFormat should work just fine. A currency instance could work even better:

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));
   }
}

This would output:

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
查看更多
甜甜的少女心
5楼-- · 2020-02-26 12:02

Use BigDecimal instead, which supports the formatting approach you seek.

This question details it: How to print formatted BigDecimal values?

查看更多
仙女界的扛把子
6楼-- · 2020-02-26 12:20

Why don't you simply Math.round(value * 100) / 100.0 ?

查看更多
登录 后发表回答