String.format() method details

JDK1.5 provides a very useful method String.format(String format, Object ... args) in the String class

Looking at the source code, I know that the java.util.Formatter.format(String, Object...) method is actually called

public static String format(String format, Object ... args) {
    return new Formatter().format(format, args).toString();
}

String.format(String format, Object ... args) The most important part of this method is its first parameter String format. As long as we master the usage of this parameter, we will also master the usage of String.format. First look at a column

String s2 = String.format("%1$tY-%1$tm-%1$te", new Date());
System.out.println(s2);

What will be printed here?

Don't rush to run it first, I believe you don't need to run it after reading it, and you will know it.

According to the JDK documentation, the String.format(String format, Object ... args) method formathas a formula that can be set.

%[argument_index$][flags][width][.precision]conversion

The content in square brackets can be omitted, and the meaning of each formula is as follows

  • argument_index: optional, is a decimal integer used to indicate the position of the argument in the argument list. The first parameter is 1$referenced , the second parameter is 2$referenced by , and so on.
  • flags: optional, used to control the output format
  • width: optional, is a positive integer, indicating the minimum length of the output
  • precision: optional, used to limit the number of output characters
  • conversion: required, the character used to indicate how to format the parameter

conversion

Let's look at a simple example:

System.out.println(String.format("我的名字叫%s", "小明")); // 打印:我的名字叫小明

Here we only use the simple expression %s. Compared with the above formula, we find that [argument_index$][flags][width][.precision] are all omitted.

Only one must be left conversion, where conversion is "s", and the percent sign % is fixed.

After [argument_index$] is omitted, it will automatically fill in the value of "Xiao Ming" into %s

Let's change the following slightly:

String.format("我叫%s,她叫%s", "小明","小方"); // 我叫小明,她叫小方

Here, Xiaoming and Xiaofang will be filled in the corresponding %s in order.

Conversion can be filled sin, so what other letters can be filled in? Of course there are some such as

  • o: the result is formatted as an octal integer
  • x: the result is formatted as hexadecimal
  • d: the result is formatted as a decimal integer
System.out.println(String.format("%o", 8)); // 10
System.out.println(String.format("%x", 16)); // 10

More conversion categories can refer to the JDK documentation java.util.Formatter class.

argument_index

Following the above example, if we want to fill in Xiaofang in the front and Xiaoming in the back, what should we do, [argument_index$]it will come in handy

String.format("我叫%2$s,她叫%1$s", "小明","小方"); // 我叫小方,她叫小明

It still starts with the percent sign %, and there is an extra , in the middle 2$, 1$that is, put the value of "Xiao Ming" 1$in its location, and "Xiao Fang" in 2$its location.

So far, we have understood the use of argument_index$and conversion, and then we will understand the usage of flagandwidth

flag&width

  • flag: used to control the output format, such as left alignment, amount separated by commas, etc.
  • width: indicates the minimum width

Let's take a look first:

String.format("%1$,d", 12302562); // 12,302,562

There is an extra comma "," here, it is flagused to separate the thousandths of the amount, of course, it %,dcan also be written as

Another example:

String.format("%1$08d", 123456);// 00123456

Here 0 means flagthat the result will be filled with zeros, 8 widthmeans at least 8 bits, and d isconversion

For other flags, please refer to the JDK documentation.

precision

Next.precision

The translation of this word means precision. We found that there is a decimal point "." in front of it, so it is not difficult to think that this is about the floating-point type.

This is only useful when the incoming data is a floating point number, neither integer nor date type data can be used

For example, if I want to round to two decimal places, then I can write:

String.format("%1$.2f", 12.12555);// 12.13

This fmeans that the incoming number is a floating-point type. If the incoming number is an integer, or if it is fchanged d, an exception will be thrown, which is clearly stated in the JDK documentation.

  • For floating point conversions 'e', ​​'E', and 'f', the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is rounded to all digits of the resulting value. If the conversion is 'a' or 'A', precision does not have to be specified.
  • For character, integer, and date/time parameter type conversions, as well as percent and line separator conversions, precision is not applicable; if precision is provided, an exception is thrown.

Date related formatting

So far, this set of expression formulas has been basically finished. This set of formulas is for basic data types and strings. What should I do if it is for time type data, such as formatting dates.

In fact, the documentation has already given instructions. The syntax of the format specifiers used to represent date and time types is as follows:

%[argument_index$][flags][width]conversion

Optional argument_index, flagsand widthare as defined above.

What is required conversionis a sequence of two characters. The first character is 't' or 'T'. The second character indicates the format used. These characters are similar to, but not identical to, those defined by GNU date and POSIX strftime(3c).

Note that it conversionis a sequence of two characters. The first character is 't' or 'T'

That is to say, when using conversion, you must first write one t, and then write other conversions.

The time type has its own set of conversions, we simply choose a few:

  • Y: Year, formatted as four digits (at least) with leading zeros if necessary, e.g. 0092 equals 92 CE in the Gregorian calendar.
  • m: Month, formatted as two digits with leading zeros if necessary, ie 01 - 13.
  • d: The day of the month, formatted as two digits with leading zeros if necessary, i.e. 01 - 31

The above three represent the year, month, and day, respectively.

If I want to display the year, I can %tY, and I can write the month %tm, remember to bringt

So does the string of complex expressions mentioned at the beginning of this article seem very simple now:

String s2 = String.format("%1$tY-%1$tm-%1$te", new Date());
System.out.println(s2); 

subsection

The usage explained in this article String.format()focuses on understanding the function of the format parameter expression. For more usage methods, please refer to the JDK documentation.

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324217496&siteId=291194637