Detailed usage in Java DecimalFormat

We often want to digital format, such as taking two decimal places, which is the most common. Java provides DecimalFormat classes to help you with the fastest speed digital format will look like you need to. Below is an example:

the java.text.DecimalFormat Import; 
 
public class TestNumberFormat {   
  public static void main (String [] args) { 
    Double PI = 3.1415927; pi // 
    // takes an integer 
    System.out.println (new DecimalFormat ( "0" ). format (PI)); // 3 
    // take an integer and two decimal places 
    System.out.println (new new DecimalFormat ( "0.00") format (PI));. //3.14 
    // takes two integers and three decimal places, insufficient to fill the integer part 0. 
    System.out.println (new new DecimalFormat ( "00.000") the format (PI).); // 03.142 
    // takes all the integer part 
    System.out.println (new DecimalFormat ( "#" ) format (pi).); / / 3 
    // count as a percentage, with two decimal places and taking 
    System.out.println (new new DecimalFormat ( "# ##%.") the format (PI).); //314.16% 
     Long C = 299792458; // speed of light
    System.out.println (new new DecimalFormat ( "E0 # #####.") The format (C).); //2.99792E8 
    // display is an integer of two scientific notation, and takes four decimal places 
    System. out.println (new new DecimalFormat ( "00 #### E0.") format (c).); //29.9792E7 
    // every three comma separated. 
    System.out.println (new DecimalFormat ( ", ###") the format (C).); // 299,792,458 
    // the embedded text format 
    System.out.println (new DecimalFormat ( "size of light per second, ## . # m ") the format (C)); 
 
  } 
 
}

DecimalFormat based mainly on two kinds of # 0 and number placeholder to specify the length. If the number is less than 0 for 0 places filled, # denotes numbers one way or another as long as possible to put in this position. The example above contains almost all the basic usage, if you want to know more, please refer to the documentation DecimalFormat class.

Guess you like

Origin www.cnblogs.com/Small-sunshine/p/11648652.html