How do I format a number in Java?

前端 未结 9 1752
自闭症患者
自闭症患者 2020-11-22 05:10

How do I format a number in Java?
What are the "Best Practices"?

Will I need to round a number before I format it?

32.302342

相关标签:
9条回答
  • 2020-11-22 05:16
    public static void formatDouble(double myDouble){
     NumberFormat numberFormatter = new DecimalFormat("##.000");
     String result = numberFormatter.format(myDouble);
     System.out.println(result);
    }
    

    For instance, if the double value passed into the formatDouble() method is 345.9372, the following will be the result: 345.937 Similarly, if the value .7697 is passed to the method, the following will be the result: .770

    0 讨论(0)
  • 2020-11-22 05:23

    Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.

    0 讨论(0)
  • 2020-11-22 05:26

    Try this:

    String.format("%.2f", 32.302342342342343);
    

    Simple and efficient.

    0 讨论(0)
  • 2020-11-22 05:29

    There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

    0 讨论(0)
  • 2020-11-22 05:32

    As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

    Use Spring's Numberformatter instead, which is thread safe.

    0 讨论(0)
  • 2020-11-22 05:38

    You and String.format() will be new best friends!

    https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

     String.format("%.2f", (double)value);
    
    0 讨论(0)
提交回复
热议问题