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. The following are common examples:
ImportJava.text.DecimalFormat; Public classtest{ Public Static voidMain (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 per second, # # #米"). Format (c));//the speed of light is 299,792,458 meters per second .}} Copy Code
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.
(RPM) Java DecimalFormat usage (numeric formatting)