Package format; Import Java.util.Formatter; public class Usingformatter { public static void Main (string[] args) { if (args.length!= 1) { System.err.println ("Usage:" + "Java Format/usingformatter"); System.exit (0); } String format = args[0]; StringBuilder StringBuilder = new StringBuilder (); Formatter Formatter = new Formatter (StringBuilder); Formatter.format ("Pi is approximately" + format + ", and E is about" + format, Math.PI, MATH.E); System.out.println (StringBuilder); } } Console call Java format/usingformatter%f Output Pi is approximately 3.141593, and E is about 2.718282 Console call Java format/usingformatter%.2f Output Pi is approximately 3.14, and E is about 2.72 Console call Java format/usingformatter%6.2f Output (with space to fill the length) Pi is approximately 3.14, and E is about 2.72 Console call Java format/usingformatter%1$.2f Output Pi is approximately 3.14, and E is about 3.14 Change Regional Settings Package format; Import Java.util.Formatter; Import Java.util.Locale; public class Usingformatter { public static void Main (string[] args) { if (args.length!= 1) { System.err.println ("Usage:" + "Java format/usingformatter <format string>"); System.exit (0); } String format = args[0]; StringBuilder StringBuilder = new StringBuilder (); Formatter Formatter = new Formatter (StringBuilder, Locale.france); Formatter.format ("Pi is approximately" + format + ", and E is about" + format, Math.PI, MATH.E); System.out.println (StringBuilder); } } Console call Java format/usingformatter%.2f Output Pi is approximately 3,14, and e are about 2,72 Using format,printf to replace the method Package format; public class Usingsystemout { public static void Main (string[] args) { if (args.length!= 1) { System.err.println ("Usage:" + "Java format/usingsystemout <format string>"); System.exit (0); } String format = args[0]; System.out.format ("Pi is approximately" + format + ", and E is approximately" + format, Math.PI, MATH.E); } } Console call Java format/usingsystemout%.2f%n Output Pi is approximately 3.14 , and E is about 2.72 |