Java - always keep two decimal places even in zeroes

后端 未结 5 947
无人及你
无人及你 2021-01-01 01:48

I am trying to keep two decimal places, even if then numbers are zeroes, using DecimalFormatter:

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


        
5条回答
  •  旧巷少年郎
    2021-01-01 02:19

    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
    

提交回复
热议问题