Formatting output numbers in Java
In actual work, you often need to set the output format of numbers, such as output in percentages or decimal places. The following is a summary.
Main classes used: Java. Text. decimalformat
1. The following two methods can be used to instantiate an object:
Decimalformat df = (decimalformat) numberformat. getinstance ();
Decimalformat DF1 = (decimalformat) decimalformat. getinstance ();
Because decimalformat inherits from numberformat.
2. Set the number of decimal places
The default number of decimal places is 3, for example:
Decimalformat df = (decimalformat) numberformat. getinstance ();
System. Out. println (DF. Format (12.3456789 ));
Output: 12.346
Now we can set the decimal point to two places using the following method:
DF. setmaximumfractiondigits (2 );
System. Out. println (DF. Format (12.3456789 ));
The output is: 12.35.
3. To convert a number to a percentage, you can use either of the following methods:
(1)
DF. applypattern ("##. ##% ");
System. Out. println (DF. Format (12.3456789 ));
System. Out. println (DF. Format (1 ));
System. Out. println (DF. Format (0.015 ));
Output: 1234.57% 100% 1.5%
(2)
DF. setmaximumfractiondigits (2 );
System. Out. println (DF. Format (12.3456789*100) + "% ");
System. Out. println (DF. Format (1*100) + "% ");
System. Out. println (DF. Format (0.015*100) + "% ");
The output is as follows:
1,234.57% 100% 1.5%
4. Set Group Size
Decimalformat DF1 = (decimalformat) decimalformat. getinstance ();
Df1.setgroupingsize (2 );
System. Out. println (df1.format (123456789 ));
Output:, 89
You can also disable group settings by using df1.setgroupingused (false);, for example:
Decimalformat DF1 = (decimalformat) decimalformat. getinstance ();
Df1.setgroupingsize (2 );
Df1.setgroupingused (false );
System. Out. println (df1.format (123456789 ));
Output: 123456789
5. Set decimal to 2 digits
Decimalformat df2 = (decimalformat) decimalformat. getinstance ();
Df2.applypattern ("0.00 ");
System. Out. println (df2.format (1.2 ));
Output: 1.20