We often need to format numbers, such as taking 2 decimal places, which is the most common. Java provides the decimalformat class to help you format numbers as quickly as possible. The following is an example.
Importjava. text. decimalformat; publicclasstestnumberformat {publicstaticvoidmain (string [] ARGs) {doublepi = 3.1415927; // The circumference rate // gets an integer system. out. println (newdecimalformat ("0 "). format (PI); // 3 // take an integer and two decimal places system. out. println (newdecimalformat ("0.00 "). format (PI); // 3.14 // take two integers and three decimal places. The less integer is filled with 0. System. out. println (New decimalformat ("00.000 "). format (PI); // 03.142 // obtain all integer parts of the system. out. println (newdecimalformat ("#"). format (PI); // 3 // count by percentage, and take two decimal places system. out. println (New decimalformat ("#. # % "). format (PI); // 314.16% longc = 299792458; // speed of light // display as scientific notation, and take the five decimal places system. out. println (newdecimalformat ("#. ##### E0 "). format (c); // 2.99792e8 // displays the scientific notation of two integers, and takes four decimal places. out. println (newdecimalformat ("00. #### E0 "). Format (c); // 29.9792e7 // each three digits are separated by commas. System. out. println (newdecimalformat (",###"). format (c); // 299,792,458 // embed the format into the text system. out. println (newdecimalformat ("the speed of light is every second, ### meters. "). Format (c ));}}
The decimalformat class mainly uses the # And 0 placeholder numbers to specify the number length. 0 indicates that if the number of digits is insufficient, it is filled with 0. # indicates that the number is pulled to this position whenever possible. The above example contains almost all the basic usage. For more information, see
Decimalformat documents.
PS: It is really convenient to process values. Write a blog to search for these problems.