Detailed description of formatting in Java

Source: Internet
Author: User

In Java, We need to rounding a number or formatting a String. We need to use String. format method or other formatting method 1. Format method: DecimalFormat df = new DecimalFormat ("#. 00 "); SimpleDateFormat sdf = new SimpleDateFormat (" yyyy-MM-dd "); Use the following methods: [java] Date date = new Date (fileTemp. lastModified (); currentUpdateTime = sdf. format (date); 2. String. format method 1. format the integer: % [index $] [ID] [minimum width] conversion method. We can see that the format string consists of four parts, the meaning of % [index $] has been mentioned above. The meaning of [minimum width] is also well understood, that is, the final integer converted The minimum number of characters in a string. Let's take a look at the meaning of the remaining two parts: logo: '-' Left alignment within the minimum width, '#' cannot be used together with "fill with 0". It is only applicable to the octal and hexadecimal formats, add a hexadecimal value before the result in the 8-hexadecimal format and add a 0x '+' before the result. The result always contains a symbol (generally, it is only applicable to the 10-hexadecimal format, if the object is BigInteger, it can be used for both octal and hexadecimal) ''plus spaces before a positive value and a negative number before a negative value (generally, this parameter is only applicable to the hexadecimal notation, if the object is BigInteger, it can be used in octal or hexadecimal notation. The '0' result will be filled with zeros. 'is only applicable to decimal notation, separate the three numbers with commas (,) ('If the parameter is a negative number, instead of adding a negative sign to the result, enclose the numbers with parentheses (the same as '+'). Conversion Method: the description above the d-decimal o-octal x or X-hexadecimal is too boring. Let's look at some specific examples. Note that most of the logo characters can be used at the same time. System. out. println (String. format ("% 1 $, 09d",-3123); System. out. println (String. format ("% 1 $ 9d",-31); System. out. println (String. format ("% 1 $-9d",-31); System. out. println (String. format ("% 1 $ (9d",-31); System. out. println (String. format ("% 1 $ # 9x", 5689); // The result is: //-0003,123 //-31 //-31 // (31) // 0x1639 2. format floating point: % [index $] [ID] [minimum width] [. precision] The conversion method shows that the floating point conversion has an "precision" option, which can control the number of digits after the decimal point. Logo: '-' is left aligned within the minimum width. It cannot be filled with "0" and '+' is used at the same time. The result will always contain a space before the ''positive value, the result of adding a negative number '0' before a negative value will be filled with zero. 'Each three digits are separated with "," (only applicable to fgG conversion) '(if the parameter is a negative number, enclose The number in parentheses instead of adding a negative number in the result (only applicable to the conversion of eEfgG). Conversion Method: 'E ', 'E' -- the result is formatted as 'F', which is expressed in the computer science notation. -- The result is formatted as 'g' or 'G' in the standard decimal notation. -- according to the actual situation, automatic selection of 'A', 'A' in general or scientific notation -- the result is formatted as a hexadecimal floating point number with valid digits and indexes. character formatting: it is very simple to format the characters. c indicates the characters, and '-' indicates the left alignment in the logo. Nothing else. 4. format the percent sign. After reading the preceding instructions, you will find that the percent sign "%" is a prefix in a special format. What should we do if we enter a percent sign? It must be escaped, but note that the escape character here is not "\", but "% ". In other words, the following statement can output "12%": System. out. println (String. format ("% 1 $ d %", 12); 5. obtain the Independent Line Separator of the Platform: System. getProperty ("line. you can obtain the Independent Line separator of the platform, but it is too cumbersome to use it in the format. Therefore, the format function comes with a platform-independent line separator, Which is String. format ("% n "). 6. format the date type. The following Date and Time conversion suffixes are defined by 'T' and 'T' conversion. These types are similar to but not exactly equivalent to those defined by GNU date and POSIX strftime (3c. Other conversion types are provided to access Java-specific functions (for example, using 'l' as the millisecond in seconds ). The following Conversion characters are used to format the time: hour in the 'H' 24-hour format, which is formatted as two digits with leading zeros (00-23) if necessary. The hour in the 'I' 12-hour format is formatted as the two digits with the leading zero when necessary, that is, 01-12. The hour in the 'K' 24-hour format, that is, 0-23. Hours in the 'l' 12-hour format, that is, 1-12. Minutes in the 'M' hour are formatted as two digits with leading zeros (00-59) if necessary. Seconds in 's' minutes are formatted as two digits with leading zeros when necessary, that is, 00-60 ("60" is a special value required to support leap seconds ). The millisecond in 'l' seconds is formatted as a three-digit number with leading zero when necessary, that is, 000-999. The millisecond In 'n' seconds is formatted as the nine-digit number with the leading zero when necessary, that is, 000000000-999999999. 'P' indicates the language environment in lowercase in the morning or afternoon, for example, "am" or "pm ". You can use the conversion prefix 'T' to forcibly convert the output to an upper-case format. The offset of 'Z' to the digital time zone in RFC 822 format of GMT, for example,-0800. 'Z' indicates a string in the abbreviated form of time zone. The Formatter language environment replaces the parameter language environment (if any ). The number of seconds since the Coordinated Universal Time (UTC) on January 1, 1970 00:00:00 to the present, that is, the difference between Long. MIN_VALUE/1000 and Long. MAX_VALUE/1000. 'Q' indicates the number of milliseconds that have elapsed since 00:00:00 on January 1, January 1, 1970 in Coordinated Universal Time (UTC), that is, the difference between Long. MIN_VALUE and Long. MAX_VALUE. The following Conversion characters are used to format the date: 'B' is the full name of the month specific to the language environment, such as "January" and "February ". 'B' indicates the abbreviation of the month specific to the language environment, such as "Jan" and "Feb ". 'H' is the same as 'B. 'A is the full name of the day of the week specific to the language environment, for example, "Sunday" and "Monday" 'A' is the abbreviation of the day of the week specific to the language environment, for example, if "Sun" and "Mon" 'C' are divided by four digits of 100, the year is formatted as two digits with leading zeros (00-99 'y' years) if necessary, it is formatted as a four-digit (at least) with a leading zero when necessary, for example, 0092 equals 92 CE of the Gregorian calendar. The last two digits of the 'y' year are formatted as the two digits with the leading zero when necessary, that is, 00-99. The number of days in a year of 'J' is formatted as a three-digit number with a leading zero when necessary. For example, for a Gregorian calendar, the value is 001-366. The 'M' month is formatted as a two-digit with a leading zero when necessary, that is, 01-13. The number of days in a month is formatted as the number of days in a month with the leading zero and double digits when necessary, that is, the number of days in 01-31 'E'. It is formatted as two digits, that is, 1-31. The following Conversion characters are used to format common date/time combinations. 'R' 24-hour time, formatted as "% tH: % tM" 't'24-hour time, formatted as "% tH: % tM: % tS ". 'R' 12-hour time, formatted as "% tI: % tM: % tS % Tp ". The location marked in the morning or afternoon ('% Tp') may be related to the language environment. 'D' date, formatted as "% tm/% td/% ty ". 'F' complete date in ISO 8601 format, formatted as "% tY-% tm-% td ". 'C' date and time, formatted as "% ta % tb % td % tT % tZ % tY", for example, "Sun Jul 20 16:17:00 EDT 1969 ". 3. Math. the Round method Math class has two methods: 1 public static long round (double a) 2 public static int round (float a) method 1 returns the long, the result is equivalent to the value of the following expression: (long) Math. floor (a + 0.5d) method 2 returns the int closest to the parameter, and the result is equivalent to the value of the following expression: (int) Math. floor (a + 0.5f) is actually rounded, but they only keep the entire number. Example: long aL = Math. round (0.4d); long bL = Math. round (0.5d); int cI = Math. round (0.4f); int dI = Math. round (0.5f); System. out. println ("aL =" + aL); System. out. println ("bL =" + bL); System. out. println ("cI =" + cI); System. out. println ("dI =" + dI); output result: aL = 0bL = 1cI = 0dI = 1 4. NumberFormat is the abstract base class of all numeric formats. This class provides interfaces for formatting and analyzing values. NumberFormat also provides methods to determine which language environment has a numerical format and their names. [Java] package com. discursive. jccook. collections; import java. text. numberFormat; public class Test {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stub Double myNumber = 23323.3323232323; double test = 0.3434; // getInstance () // return the default value format of the current default language environment. String myString = NumberFormat. getInstance (). format (myNumber); System. out. println (myString); // getCurrencyInstance () returns the general format of the current default language environment, myString = NumberFormat. getCurrencyInstance (). format (myNumber); System. out. println (myString); // getNumberInstance () returns the general value format of the current default language environment. MyString = NumberFormat. getNumberInstance (). format (myNumber); System. out. println (myString); // getPercentInstance () returns the percentage format of the current default language environment. MyString = NumberFormat. getPercentInstance (). format (test); System. out. println (myString); // setMaximumFractionDigits (int) sets the maximum number of digits allowed in the decimal part of the value. // SetMaximumIntegerDigits (int) specifies the maximum number of digits allowed in the integer part of the value. // SetMinimumFractionDigits (int) specifies the minimum number of digits allowed in the decimal part of the value. // SetMinimumIntegerDigits (int) specifies the minimum number of digits allowed in the integer part of the value. numberFormat format = NumberFormat. getInstance (); format. setMinimumFractionDigits (3); format. setMaximumFractionDigits (5); format. setMaximumIntegerDigits (10); format. setMinimumIntegerDigits (0); System. out. println (format. format (2132323213.23266666666) ;}}result: 23,323.332 $23,323.3323, 323.33234% 2,132,323,213.23267

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.