Double decimal formatting in Java

后端 未结 14 1227
囚心锁ツ
囚心锁ツ 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:33

    With Java 8, you can use format method..: -

    System.out.format("%.2f", 4.0); // OR
    
    System.out.printf("%.2f", 4.0); 
    
    • f is used for floating point value..
    • 2 after decimal denotes, number of decimal places after .

    For most Java versions, you can use DecimalFormat: -

        DecimalFormat formatter = new DecimalFormat("#0.00");
        double d = 4.0;
        System.out.println(formatter.format(d));
    

提交回复
热议问题