Double decimal formatting in Java

后端 未结 14 1465
囚心锁ツ
囚心锁ツ 2020-11-22 05:17

I\'m having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it\'s 4.00 instead?

14条回答
  •  离开以前
    2020-11-22 05:43

    You can use any one of the below methods

    1. If you are using java.text.DecimalFormat

      DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance(); 
      decimalFormat.setMinimumFractionDigits(2); 
      System.out.println(decimalFormat.format(4.0));
      

      OR

      DecimalFormat decimalFormat =  new DecimalFormat("#0.00"); 
      System.out.println(decimalFormat.format(4.0)); 
      
    2. If you want to convert it into simple string format

      System.out.println(String.format("%.2f", 4.0)); 
      

    All the above code will print 4.00

提交回复
热议问题