I encountered a problem at work today, how to keep two significant digits in double type numbers. Baidu will have a lot of answers, and then I found a relatively simple paragraph and shared it with everyone:
Formatting numbers, such as to 2 decimal places, is the most common. Java provides the DecimalFormat class to help you format numbers the way you need them in the fastest way possible. Below is an example:
[java] view plaincopyprint? importjava.text.DecimalFormat; publicclassTestNumberFormat{ publicstaticvoidmain(String[]args){ doublepi=3.1415927; //pi // take an integer System.out.println(newDecimalFormat("0").format(pi)); //3 // take one integer and two decimals System.out.println(newDecimalFormat("0.00").format(pi)); //3.14 //Take two integers and three decimals, and fill in the missing part of the integer with 0. System.out.println(new DecimalFormat("00.000").format(pi));// 03.142 // get all integer parts 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 in scientific notation and take five decimal places System.out.println(newDecimalFormat("#.#####E0").format(c)); //2.99792E8 //display as two-digit integer scientific notation, and take four decimal places System.out.println(newDecimalFormat("00.####E0").format(c)); //29.9792E7 // Each three is separated by a comma. System.out.println(newDecimalFormat(",###").format(c)); //299,792,458 // embed formatting into text System.out.println(newDecimalFormat("The speed of light is per second, ###meters.").format(c)); } }
The DecimalFormat class mainly relies on the # and 0 placeholders to specify the length of the number. 0 means padding with 0 if there are not enough digits, # means pulling the number to this position whenever possible. The above example covers almost all the basic usage.