reproduced for personal study reference only, the following view please go to the original source:http://blog.csdn.net/wangchangshuai0010/article/details/8577982
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 a single-digit integerSystem.out.println (Newdecimalformat ("0"). Format (pi));//3//take an integer and a two decimal placeSystem.out.println (Newdecimalformat ("0.00"). Format (pi));//3.14//take two-bit integers and three decimal places, and 0 fill in the less-than-integer parts. System.out.println (NewDecimalFormat ("00.000"). Format (pi));//03.142//take all integer partsSystem.out.println (Newdecimalformat ("#"). Format (pi));//3//count as a percentage and take two decimal placesSystem.out.println (NewDecimalFormat ("#.##%"). Format (pi));//314.16%LONGC= 299792458;//Speed of Light//Display as scientific notation, and take five decimal placesSystem.out.println (Newdecimalformat ("#.#### #E0"). Format (c));//2.99792E8//scientific notation shown as a two-bit integer, with four decimal placesSystem.out.println (Newdecimalformat ("00.### #E0"). Format (c));//29.9792E7//each three bits is delimited by commas. System.out.println (Newdecimalformat (", # # #"). Format (c));//299,792,458//embed formatting into textSystem.out.println (Newdecimalformat ("The speed of light is the size of every 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.
"Reprint" Java DecimalFormat usage