DecimalFormat can be used to format numbers, for example, to set how many decimal places are reserved, set number separators, and so on.
Before you say the method, let's introduce some of its commonly used pattern placeholders:
01 Digits
# A number that does not include 0
. Placeholder for decimal separator
, the placeholder for the grouping separator
Here is a simple example of how to use it:
Public Static voidMain (string[] args) {DecimalFormat df1=NewDecimalFormat ("#.#"); DecimalFormat DF2=NewDecimalFormat ("###.###"); DecimalFormat df3=NewDecimalFormat ("0.0"); DecimalFormat Df4=NewDecimalFormat ("000.000"); DecimalFormat Df5=NewDecimalFormat ("0,0.00"); Doublenum = 12.34; SYSTEM.OUT.PRINTLN (Df1.format (num)); SYSTEM.OUT.PRINTLN (Df2.format (num)); SYSTEM.OUT.PRINTLN (Df3.format (num)); SYSTEM.OUT.PRINTLN (Df4.format (num)); SYSTEM.OUT.PRINTLN (Df5.format (num)); }
The output is as follows:
12.3
12.34
12.3
012.340
1,2.34
Java Basics--decimalformat Formatting numbers