Double decimal formatting in Java

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

    You could always use the static method printf from System.out - you'd then implement the corresponding formatter; this saves heap space in which other examples required you to do.

    Ex:

    System.out.format("%.4f %n", 4.0); 
    
    System.out.printf("%.2f %n", 4.0); 
    

    Saves heap space which is a pretty big bonus, nonetheless I hold the opinion that this example is much more manageable than any other answer, especially since most programmers know the printf function from C (Java changes the function/method slightly though).

提交回复
热议问题