JAVA string formatting - the use of String.format()
introduction
Methods of the String class format()
are used to create formatted strings and concatenate multiple string objects. Familiar with C language should remember sprintf()
the method of C language, the two have similarities. format()
There are two overloaded forms of the method.
overload
// 使用当前本地区域对象(Locale.getDefault()),制定字符串格式和参数生成格式化的字符串
String String.format(String fmt, Object... args);
// 自定义本地区域对象,制定字符串格式和参数生成格式化的字符串
String String.format(Locale locale, String fmt, Object... args);
Placeholder
The format description can have up to 5 parts (excluding the % symbol). The [] symbols below are all optional items, so only % and type are necessary. The order of the format description is specified and must be Chapter specified in this order.
Example:
When there are more than one parameter, add the new parameter to the back, so there will be 3 parameters to call format()
instead of two, and in the first parameter, that is, in the format string, there will be two different formats Optimization setting, that is, a combination of characters beginning with two %, the second one will be applied to the first %, and the third parameter will be used on the second %, that is, the parameters will be applied to the above in order. %
"
int one = 123456789;
double two = 123456.789;
String s = String.format("第一个参数:%,d 第二个参数:%,.2f", one, two);
System.out.println(s);
conversion character
Converter flag
Format the string
Example - will "hello"
format as "hello "
(left-aligned)
String raw = "hello word";
String str = String.format("|%-15s|", raw);
System.out.println(str);
Format an integer
Example - Display -1000 as (1,000)
int num = -1000;
String str = String.format("%(,d", num);
System.out.println(str);
[
Format floating point numbers
double num = 123.456789;
System.out.print(String.format("浮点类型:%.2f %n", num));
System.out.print(String.format("十六进制浮点类型:%a %n", num));
System.out.print(String.format("通用浮点类型:%g ", num));
Format datetime
- Date Converter
- time converter
example
Date date = new Date();
System.out.printf("全部日期和时间信息:%tc%n",date);
System.out.printf("年-月-日格式:%tF%n",date);
System.out.printf("月/日/年格式:%tD%n",date);
System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);
System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);
System.out.printf("HH:MM格式(24时制):%tR",date);