java format summary

The powerful Java format
in Java allows us to be some kind of format the specified object, so we want to get the formatting styles.
Format
introduces the java.text Format package
Foramt is an abstract base class, subclass must implement specific

format(Object obj, StringBuffer toAppendTo, FieldPosition pos)

with

parseObject(String source, ParsePosition pos)

Two abstract methods.
A method for an object format specified string format mode
parseObject a method for re-parse the string to an object
directly include subclasses of Format DateFormat, NumberFormat, and MessageFormat. The following describes one by one
1.DateFormat
DateFormat based on the current date and time formatting locale.
DateFormat is an abstract class, so can not directly create a new instance of an object. But class provides factory methods that we use for our convenience.

- getDateInstance()方法,获取格式化的日期,输出样式:2015-12-10
- getDateTimeInstance()方法,获取格式化的日期和时间,输出样式:2015-12-10 10:21:41
- getTimeInstance()方法,获取格式化的时间,输出样式:10:21:41
- getInstance()方法,获取格式化的日期和时间,输出样式:15-12-10 上午10:21

Maybe you will find that allowing these factories release we pass an int parameter, which allows us to set formatting style to give us relatively good results. Table corresponding to the different output styles and style values (constant values which are DateFormat class)
style value Date Time
SHORT 15-12-10 AM 10:08
MEDIUM, 2015-12-10 10:09:23
a LONG years, 2015 at 10:09:40 on December 10
FULL 2015 Nian 12 Yue Thursday 10 10:17:30 CST
the DEFAULT 2015-12-10 10:18:07
Of course, you can also specify the locale to acquire the language environment date and time formatting,

DateFormat format = DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.CANADA);//获取加拿大的格式化日期

Maybe you want to ask a question, above format you did not want me ah. Well, there's a good thing
SimpleDateFormat
SimpleDateFormat is a concrete class DateFormat, which allows us to specify the format mode in order to get our ideal format date and time.
By the constructor SimpleDateFormat format mode, you can pass a string or add a format pattern string by applyPattern (String pattern) method.
For the pattern string format, the API provides a rich schema elements for us, listed below several common mode element
letter date or time elements exemplary
y 2015
of the month of M 12 is
W is the number of weeks of 50
W is the month 02 weeks
344 days d on the
days in d month 10
02 F in the month week
days E of the week Thursday, Thu
a AM / the PM marks PM, PM
hours in H day (0 to 23) 21
hours k in one day (1 to 24) 21
number K am / pm in hours (0 to 11) 09
number h am / pm in hours (1 to 12 is) 09
m hours, minutes number 31 is
S minutes 08 seconds
S 716 milliseconds
if you set Locale then have different display formats, such as if set Locale.ENGLISH, E will be displayed in English format, a display as AM or PM

= New new DATE DATE DATE ();
SimpleDateFormat format = new new SimpleDateFormat ( "Today is yyyy-MM-dd E hh: mm: ss, is the first DD, yyyy day, in the month dd is the first day");
System.out .println (format.format (date));
will output: today is Thursday 2015-12-10 09:38:16, 2015 the first 344 days, in the first 10 days of the month
2.NumberFormat
the NumberFormat based on the current format numbers locale
NumberFormat is also an abstract base class, instance of an object may be acquired using the factory method in the API
1.getCurrencyInstance () method, according to obtain currency numeric format the current locale. Locale object transfer monetary values, may be acquired in the format specified locale, such as
the NumberFormat = NumberFormat.getCurrencyInstance the format (Locale.CANADA);
System.out.println (format.format (439.6));
will output: $ 439.60
2.getInstance ( ) and getNumberInstance () method of the conventional numerical format are acquired
3.getIntegerInstance () method to get a conventional integer format, if the decimal value to be formatted, it will be rounded to the nearest integer value
acquisition method 4.getPercentInstance () percentage numeric format
NumberFormat two subclasses DecimalFormat embodied and A ChoiceFormat
DecimalFormat
DecimalFormat with similar SimpleDateFormat, allows us to specify the format mode acquiring numerical format we want
DecimalFormat class values for the fractional part, the default display 3 decimal places after the decimal point in removing the exceeding 3 when bit part, will be rounded to the nearest numerical value formatted output. Indifferent we can set the default
setMaximumFractionDigits (int newValue) method, set the fractional portion of the maximum allowable number of digits
setMinimumFractionDigits (int newValue) method, set the minimum number of digits allowed in the fractional part, if the original number of decimal places is not enough then, it will be zeros.
For the integer part of the value, a default set of three digits is displayed, the same can also customize this we used setGroupingSize (int i) method, provided the number of bits in a packet group.
setGroupingUsed (boolean value) whether the packet is provided a method, true indication, false indicates ungrouping
setMaximumIntegerDigits (int newValue) method sets the integer portion of the maximum allowable number of digits
setMinimumIntegerDigits (int newValue) method sets the integer part of the minimum number of digits allowed
in `` `` construction method, the model allows us to pass the format string value we want to format the output format pattern comprising the following elements

Represents a number 0, the value is not formatted would complement bits 0

Represents a number, formatted value is not enough number of bits ignored

. Decimal separator placeholder
, the placeholder packet delimiter

  • The default negative prefix
    % The value is multiplied by 100 and shown as a percentage
    \ u2030 the value is multiplied by 1000 and displayed as per mille
    again
    DecimalFormat new new DecimalFormat format1 = ( "# \ u2030");
    System.out.println (format1.format ( 0.3345)); // output 334 ‰

DecimalFormat format2 = new DecimalFormat("##.##");
System.out.println(format2.format(12.345));//输出12.35

DecimalFormat format3 = new DecimalFormat(“0000.00”);
System.out.println(format3.format(12.345));//输出0012.35

= New new DecimalFormat format4 DecimalFormat (. "# ##%");
System.out.println (format4.format (12.345)); // Output% 1234.5
A ChoiceFormat
A ChoiceFormat allows formatting applied to a range of numbers, generally MessageFormat used together. ChoiceFormat a receiving array format array limits and a construction method, the length of the two arrays must be equal, for example:
limits = {1,2,3,4,5,6,7}
Formats = { "the Sun", " mon "," Tue "," Wed "," Thur "," Fri "," Sat "}
Limits array is actually a section, can be opened and closed, and must be in ascending order, if not in ascending order, the result is formatted will be incorrect, you can also use \ u221E (to represent infinity).
ChoiceFormat match formula
limit [j] <= X < limit [j + 1]
where X represents the method using the passed value format, j represents the index into the array limit. If and only if the establishment of the above formula, X match j, if not match, it will be too small or too large an X, limits matching the first index or the last index of the array, then use the matching index in the array limits , to the formats array to find the same index value. Examples:
Double [] = {Limits. 3,. 4,. 5,. 6,. 7,. 8,. 9};
String [] = {Formats "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
The format A ChoiceFormat new new = A ChoiceFormat (Limits, Formats);
System.out.println (format.format (2.5)); // will output "Monday"
/ * between 3 and 3.6 is between 4, it will match 3, Also, because the index limits the array 3 is 0, the value of the formats in the array will be indexed according to Xu 0, i.e., the output of "Monday"
/
System.out.println (format.format (3.6));
the following classes look ChoiceFormat several common methods
1.nextDouble (double d) static method to find the minimum double greater than d, and limits used in the array, the array is formed such that limits a right open interval array, e.g.
limits = {0,1, ChoiceFormat. nextDouble (. 1)}
2.nextDouble (double d, Boolean positive) static method, positive if the parameter is true, that find the minimum of double greater than d; positive if the argument is false, indicates to find the maximum value of double less than d, so the limits can form a left-open interval array.
3.previousDouble (double d) static method to find less than double the maximum value of d
constructor class ChoiceFormat also allows us to pass a pattern string, format string formatting method will be based on this mode of operation. A format pattern element as follows:
DoubleNum [placeholder] formatStr
placeholders may be used #, <, \ u2264 (<
A ChoiceFormat new new CF2 = A ChoiceFormat ( "IS. 1. 1 # |. 1 <IS More Within last. 1");
System.out.println (cf.format (. 1)); // Output "IS. 1"
System.out.println (CF2. format (2)); // output "iS More Within last. 1"
System.out.println (cf.format (0)); // output "is 1"
by the above example can be seen, each of the pattern string when can add spaces before and after to beautify the code, and must be written in ascending order, otherwise there will be an exception java.lang.IllegalArgumentException operating modes used between elements "| |" split "."
Watch ChoiceFormat class source we learned that, in fact, internally, are converted into the pattern string or two arrays limits and formats. In the source code
public A ChoiceFormat (String newPattern) {
applyPattern (newPattern);
}
/
portion of source applyPattern (newPattern) method
* /
public void the applyPattern (String newPattern) {
...
to choiceLimits = new new Double [COUNT];
System.arraycopy (newChoiceLimits, 0, choiceLimits, 0, count)
= new new String choiceFormats [COUNT];
System.arraycopy (newChoiceFormats, 0, choiceFormats, 0, COUNT);
...
}
can be seen ChoiceFormat (String newPattern) called applyPattern (String newPattern) method, the method newPattern string applyPattern analyzing, and then place the parsed data to a private property ChoiceFormat class two double [] choiceLimits and String [] choiceFormats, and then to use the formatting method.
3.MessageFormat
the MessageFormat provides a way to generate a locale-independent connection message.
MessageFormat format commonly used static method, the method takes a string and a set of model objects (object array), formatted according to a schema object into the model, and then returns the result string.
MessageFormat format of pattern elements (FormatElement) form is as follows:
{argumentIndex}
{argumentIndex, FormatType}
{argumentIndex, FormatType, FormatStyle}
where the index argumentIndex object in the array, starting from 0,
FormatType including number, date, time, choice,
FormatStyle comprising short, medium, long, full, integer, currency, percent, SubformatPattern ( child mode),
inside MessageFormat class, and FormatStyle FormatType actually creating Format example format element
number corresponds to the NumberFormat, which corresponds to the sub-formats DecimalFormat
DATE and time correspond to the DateFormat, whose qualifications correspond to the SimpleDateFormat
Choice correspond ChoiceFormat
say no meaning to more than a few chestnuts:
you can directly use the static method format MessageFormat class, like this:
/ ** this is an example of source annotation

  • In this example, a first format Static method parameter is a string type,
  • That pattern string, the second parameter is a variable parameter, is actually an array of a type Object.
  • Using "{}" in the pattern string identifying a FormatElement. "{}" Object corresponding value in the array ArgumentIndex response index.
    * /
    Int = Planet. 7;
    String Event = "A disturbance in The Force";
    String MessageFormat.format Result = ( "{At. 1, Time {ON}. 1, DATE}, there WAS ON Planet {2} {0, Number ., Integer} ",
    Planet, new new a Date (), Event);
    System.out.println (Result);
    // output: At 20:39:15 on 2015-12-11, there was a disturbance in the Force on planet 7.
    you can also use the constructor incoming MessageFormat pattern string (string mode), and then call the general format method here is not to give the chestnuts.
    We are not only permitted to use the MessageFormat class provides default FormatElement to format these objects, you can also set your own Format format these objects Object.
    / ** In this example, MessageFormat ChoiceFormat are used in combination, and
  • MessageFormat class has three methods we are concerned about the value of
  • 1.setFormatByArgumentIndex(int argumentIndex, Format newFormat)//
  • 2.setFormats(Format[] newFormats)
  • 3.setFormat(int formatElementIndex, Format newFormat)
  • In this example the, in the pattern string MessageFormat FormatElement (i.e., the content of {}) in
  • Where 0 is the index will use ChoiceFormat format to format.
  • If you still have FormatElement in Format set, the format will be a recursive call method of MessageFormat.
    * /
    The MessageFormat form = new new the MessageFormat ( "of The Disk" {. 1} "the contains {0}.");
    Double [] filelimits = {0,. 1, 2};
    String [] FilePart = { "NO Files", "One File "," {0, Number} Files "};
    A ChoiceFormat fileform new new = A ChoiceFormat (filelimits, FilePart);
    form.setFormatByArgumentIndex (0, fileform);
    int fileCount = 1273;
    String DiskName =" mydisk ";
    Object [] = testArgs Long new new {(fileCount), DiskName};
    System.out.println (form.format (testArgs));
    // output: Disk of the "mydisk" Files the contains 1,273.
    format method 4.String class
    format method using placeholder character format
    of a conventional type, numeric type character type and format placeholders:
    % [index ] [ Mark knowledge ] [ most small width degree ] [ . fine degree ] turn change symbol day period with Time between class type of Take up Place symbol grid formula ] [Identifier] [minimum width] [the precision] conversion operation date and time format type placeholder:.% [Index [identifier] [minimum width] conversion operation
    and do not correspond to the parameter placeholder character format:
    % [identified] [minimum width] conversion operation
    wherein the index value indicating the position in the parameter list
    of available identifier:
    identifies the meaning of
  • The minimum width in the left-justified, can not be used with identification 0
    0 When the content is less than the length of the minimum width, then filled to the left with 0

To 8 decimal and hexadecimal, octal before adding a decimal before adding 0,16 0x

  • Results always contains a + or -
    spaces spaces before positive, negative numbers preceded by - number
    , decimal only, with every three digits, separated
    (if the result is negative, the live parentheses, without displaying the symbol
    available conversion specifier:
    conversion operator meaning
    b Boolean type, as long as the arguments of the non-Boolean false, strings are formatted as true, false otherwise string
    independent of newline n platform, can also be System.getProperty ( "line .separator ") Get
    f float type (decimal). 9 show significant figures, and will be rounded off as 99.99
    A floating point type (hex)
    E index type as +. 5 9.38e
    G floating point type ( ratio% f,% a shorter length, displaying six significant digits, and will be rounded off)
    S string type
    c character type

String result1 = String.format ( "% d years old this year, Xiao Ming, who lives in% s, his monthly wage% .2f", 25, "Beijing", 6633.435);
System.out.println (result1); / I / O: Xiao Ming, 25, who lives in Beijing, his monthly wage 6633.44
/ ************************************************************ ************************************************************ /
Double NUM = 123.4567899;
String result2 String.format = ( "E%", NUM);
System.out.println (result2); // output: 1.234568e + 02

Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43488547/article/details/103752396