We often have to format numbers, such as 2 decimal places, which is the most common. Java provides the DecimalFormat class, which helps you to format numbers as quickly as you like. Here is an example:
Importjava.text.DecimalFormat; publicclasstestnumberformat{Publicstaticvoidmain (String[]args) {doublepi=3.1415927;//pi//Take one-bit integer S Ystem.out.println (Newdecimalformat ("0"). Format (pi)); 3//Take one-bit integer and two-bit decimal System.out.println (Newdecimalformat ("0.00"). Format (pi)); 3.14//Take two-bit integers and three-bit decimals, and the integral parts are filled with 0. System.out.println (New DecimalFormat ("00.000"). Format (pi));//03.142//Take all integral parts System.out.println (newdecimalform At ("#"). Format (pi)); 3//count in percent and take two decimal System.out.println (new DecimalFormat ("#.##%"). Format (pi)); 314.16% longc=299792458; The speed of light//is shown as scientific notation and takes five decimal System.out.println (Newdecimalformat ("#.#### #E0"). Format (c)); 2.99792E8//Displays the scientific notation for two-bit integers and takes four decimal System.out.println (Newdecimalformat ("00.### #E0"). Format (c)); 29.9792E7//Every three bits are separated by commas. System.out.println (Newdecimalformat (", # # #"). Format (c)); 299,792,458//Embed the format in the text System.out.println (Newdecimalformat ("The speed of light is per second, # # #米. "). Format (c)); } }
The DecimalFormat class mainly relies on # and 2 placeholder symbols to specify the number length. 0 indicates that if the number of bits is not sufficient, fill with 0, # indicates that the number is pulled up to this position whenever possible. The above example contains almost all the basic usage, if you want to learn more, please refer to the DecimalFormat class documentation.
(Original address: http://blog.csdn.net/wangchangshuai0010/article/details/8577982)
[Go] Java decimalformat usage