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 integer
- System.out.println (Newdecimalformat ("0"). Format (pi)); //3
- Take an integer and a two decimal place
- System.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 (new DecimalFormat ("00.000"). Format (pi)); 03.142
- Take all of the integral parts of the
- System.out.println (Newdecimalformat ("#"). Format (pi)); //3
- Count as a 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 five decimal places
- System.out.println (Newdecimalformat ("#.#### #E0"). Format (c)); //2.99792e8
- Scientific notation shown as a two-bit integer, with four decimal places
- System.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 text
- System.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.
DecimalFormat class in Java