We often format numbers, such as taking 2 decimal places, which is the most common one. Java provides the DecimalFormat class to help you format numbers as fast as you need. Here is an example:
importjava.text.DecimalFormat; public class TestNumberFormat{ public static void main(String[]args){ doublepi=3.1415927; //Pit//Pit a single integer System.out.println(newDecimalFormat("0").format(pi)); //3 //Pit a single integer and two decimal places System.out.println(newDecimalFormat("0.00").format(pi)); //3.14 //Pit two integers and three decimal places, and the insufficient integers are filled with 0. System.out.println(new DecimalFormat("00.000").format(pi));// 03.142 // Take all integer parts System.out.println(newDecimalFormat("#").format(pi)); //3 //Count as a percentage and take two decimals System.out.println(new DecimalFormat("#.##%").format(pi)); //314.16% longc=299792458; //The speed of light//The display is as a scientific notation method, and the five decimal places are taken System.out.println(newDecimalFormat("#.####E0").format(c)); //2.99792E8 //The display is as a scientific notation method, and the four decimal places are taken System.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 //Embing the format into the text System.out.println(newDecimalFormat("The speed of light is per second,### meters.").format(c)); } }The DecimalFormat class mainly relies on two placeholders, # and 0, to specify the length of the number. 0 means that if the number of digits is insufficient, it will be filled with 0, and # means that the number will be pulled to this position whenever possible. The above example contains almost all the basic usages. If you want to know more, please refer to the documentation of the DecimalFormat class.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.