Detailed usage of DecimalFormat in Java, javadecimalformat
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; public class TestNumberFormat {public static void main (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 the documentation of the DecimalFormat class.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.