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
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
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.
Try this:
String.format("%.2f", 32.302342342342343);
Simple and efficient.
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).
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.
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);