Data formatted by 眀海 棠 文集 1.0

xiaoxiao2021-03-06  1

Data formatted by 眀海 棠 文集 1.0

The Java.Text package allows text messages, date, and values ​​to be formatted by way of unrelated to a particular language.

1. Data format related class introduction

class

Features

Java.util. *

Locale

Specific combination of language and region

ResourceBundle

ListResourceBundle

PropertyResourceBundle

Get information in localized resources (which can be expressed as class and resource files)

Calendar

Gregoriancalendar

Calendar support

Timezone

SimpleTimezone

Time zone support

Currency

Separate processing and currency related operations

Java.text. *

Format

Numberformat

DecimalFormat

format

Format numbers, currency, and percentage

ChoiceFormat

Processing plural form

DateFormat

SimpleDateFormat

Date and time formatting

MessageFormat

Message formatting

DecimalFormatsymbols, DateFormatsymbols

Custom format symbol set

FIELDPSITION

Format and its subclass are used to identify fields in formatted output

Collator

RulebasedCollator

String operation

Compare string

CollationElementIterator

Get an enumeration information of a single character in a string

COLLATIONKEY

Optimize comparative performance

Breakiterator

Get individual information in the text, such as characters, words, sentences, etc.

Java.lang. *

Character

Check the character properties

2. Internationalization and MessageFormat class

MessageFormat runs the format of the variable in the developer's output text, which is mainly used for internationalization. It is a powerful class, just like the example below:

String message =

"Once Upon a Time ({1, Date}, Around About {1, Time, Short}), There"

"Was a humble development, geppto who slaved for"

"{0, Number, Integer} Days with {2, Number, Percent} Complete User"

Requirements. "

Object [] variables =

New Object [] {new integer (4), new date (), new double (0.21)}

String Output = MessageFormat.Format (Message, Variables);

System.out.println (output); OUTPUT;

The information hidden in the information is a short code of the format of the output. The output is as follows:

Once Upon A Time (Nov 3, 2002, Around About 1:35 AM), There Was A Humble Developer Named GePpetto WHO SLAVED For 4 Days with 21% Complete User Requirements.

If the same information needs to be repeated but the value of the variable is different, create a MessageFormat object and give information. Here is the correct version of the above example:

// String Output = MessageFormat.Format (Message, Variables);

// To:

MessageFormat Formatter = new messageformat (message); string output = formatter.format (variables);

In addition to processing dates, time, numbers, and percentages, MessageFormat can also handle money, run more digital format control and allow you to specify ChoiceFormat.

MessageFormat is an excellent class that should be used frequently but yet. Its maximum disadvantage is that the data is passed as a variable rather than a Properties object. A simple solution is to write a package, which will prepare the string as the result of formatting, convert the Properties's key to a array index, the order is the order of Properties.Keys () returned.

3. Value formatting

3.1. About NumberFormat

If you are from the United States, you will place a comma in the middle of the larger value to express thousands and millions (wait, using a comma every three values). For floating point numbers, you will place a decimal point between the integer part and the fractional portion. For money, currency symbols are placed in front of the amount. If you have never arrived outside the United States, you may not care about the British currency formatted with pound (£), or use the Euro (€) to the currency of other European countries.

For currency we do care, we can format them using Numberformat and their related classes. Developers use the NumberFormat class to read the values ​​entered by the user and format the output to be displayed to the user.

In Java's I / O, there is no so-called type, whether it is int, long, double ... Finally, it is output with String, so if you want to output it in a specific format, you need to provide two categories from Java Java. .Text.NumberFormat and Java.Text.DecimalFormat format the digital to the output.

When starting using NumberFormat, you should get NumberFormat entities, paragraph 12, in paragraph 12, is used to set the number of digits and decimal numbers, and SETMINIMUMUMFRACTIONDIGITS is also the same. These settings are conflicted, and Java is based on the final setting.

Import java.text. *;

Public class myformat {

Public myFormat () {

Numberformat nf = Numberformat.getInstance ();

Double dblnum = math.pi;

System.out.println (DBLNUM);

Nf.setmaximumUmintegerdigits (5);

Nf.SETMINIMUMFRActionDIGITS (4);

System.out.println ("PI:" NF.Format (dblnum));

}

Public static void main (String [] args) {

MyFormat myFormat1 = new myFormat ();

}

}

Similar to DATEFORMAT, NumberFormat is an abstract class. You will never create instances - the opposite, you always use its subclass. Although the subclass can be created directly through the constructor of the subclass, the NumberFormat class provides a series of getxxxInstance () methods to obtain specific regional versions of different types of numerical classes. There are five such methods: getcurrencyinstance ()

GetInstance ()

GetintegerInstance ()

GetNumberinstance ()

getPercentInstance ()

Which method for specific use depends on the value type you want to display (or you want to accept the input type). Each method provides two versions - a version for the current region, another version accepts a local as a parameter to specify a different area.

The basic process using NumberFormat is to obtain an instance and use this instance. Picking the appropriate instance does need a trust of thinking. Usually you don't want to use universal GetInstance or getNumberInstance (), because you don't know what you will get. Instead, you will use methods like getIntegerInstance () because you want to display some content as an integer without any small value. Listing 1 shows this, we show the value 54321 as a format suitable for the US and Germany.

Listing 1. Using NumberFormat

Import java.text. *;

Import java.util. *;

Public class integersample {

Public static void main (string args []) {

Int Amount = 54321;

Numberformat USFormat =

Numberformat.getintegerInstance (locale.us);

System.out.println (Usformat.Format (Amount));

Numberformat germanFormat =

Numberformat.GetintegerInstance (locale.germany);

System.out.println (GermanFormat.Format (Amount));

}

}

Running this code will produce the output shown in Listing 2. Note the comma separator in the first format (US) and the dot divid in the second format.

Listing 2. NumberFormat output

54,321

54.321

Although NumberFormat is an abstract class, and you will use its instance by a variety of methods like getIntegerInstance (), but the DecimalFormat class provides a specific version of the class. You can explicitly specify the character mode to determine how to display positive, negative numbers, decimal, and indices. If you don't like a predefined format for different regions, you can create your own format. (Inside, perhaps NumberFormat is DecimalFormat.).

3.2. Use currency to conduct currency calculations

The getCurrency () and setCurrency () methods mentioned earlier returns an instance of the new Java.util.currency class. This class allows access to ISO 4217 currency code in different countries. Although you can use it with NumberFormat since getcurrencyinstance (), you can never get or display money symbols in a certain region in addition to their digital display. With the Currency class, you can easily do this now.

As mentioned earlier, the currency code comes from ISO 4217. Currency.GetInstance () will return a valid Currency object by incorporating the actual alphabetic code of a local Locale or currency. Numberformat's getCurrency () method will do the same thing after the currency instance of creating a particular region. Listing 7 shows how to get currency instances, and how to format the value to be displayed as a currency. Remember that these conversions are only used for display. If you need to convert the amount between the currency, you should convert before determining how to display the value. Listing 7. Using getCurrencyinstance () and Currency

Import java.text. *;

Import java.util. *;

Import java.awt. *;

Import javax.swing. *;

Public class currencysample {

Public static void main (string args []) {

StringBuffer Buffer = New StringBuffer (100);

Currency DOLLARS = CURRENCY.GETInstance ("USD");

Currency Pounds = currency.getinstance (local.uk);

Buffer.Append ("Dollars:");

Buffer.Append (DOLLARS.GETSYMBOL ());

Buffer.Append ("/ n");

Buffer.Append ("Pound Sterling:");

Buffer.Append (Pounds.getsymbol ());

Buffer.Append ("/ n ----- / n");

Double Amount = 5000.25;

Numberformat USFormat = NumberFormat.getcurrencyinstance (locale.us);

Buffer.Append ("Symbol:");

Buffer.append (usformat.getcurrency (). getsymbol ());

Buffer.Append ("/ n");

Buffer.Append (USMMAT.FORMAT (Amount));

Buffer.Append ("/ n");

Numberformat germanFormat =

Numberformat.getcurrencyinstance (locale.germany);

Buffer.Append ("Symbol:");

Buffer.Append (GermanFormat.getCurrency (). getsymbol ());

Buffer.Append ("/ n");

Buffer.Append (GermanFormat.Format (Amount));

JFrame frame = new jframe ("currency");

Frame.setDefaultCloseOperation (jframe.exit_on_close);

Jtextarea Ta = new jtextarea (buffer.tostring ());

Jscrollpane Pane = New JscrollPane (TA);

Frame.getContentPane (). Add (PANE, BORDERLAYOUT.Center);

Frame.setsize (200, 200);

Frame.show ();

}

}

Unfortunately, currency symbols returned for the euro or pounds are not actual symbols, but three currency code (from ISO 4217). However, in the case of getCurrencyInstance (), the actual symbol will be displayed, 3.3. DecimalFormat

Numberformat.getInstance () method Returns an instance of NumberFormat (actually a subclass of NumberFormat, such as DecimalFormat), which is suitable for formatting a number in accordance with local settings. You can also use non-default areas, such as Germany. Then format the figures based on a specific regional rule. This program can also use a simple form:

Numberformat.getInstance (). Format (1234.56)

But save a format and then reuse more efficient. Internationalization is a big problem when formatting numbers.

The other is the effective control of the format, such as the number of bits specified in the fractional portion, and below is a simple example of solving this problem:

Import java.text.decimalformat;

Import java.util.locale;

Public class decimalformat2 {

Public static void main (string args []) {

// Get local default format decimalformat df1 = new decimalformat ("####. 000");

System.out.println (Df1.Format (1234.56));

/ / Get the format of Germany

Locale.SetDefault (locale.german);

DecimalFormat DF2 = New DecimalFormat ("####. 000");

System.out.println (Df2.Format (1234.56));

}

}

In this example, the format of the number is set, and the symbol like "####. 000" is used. This pattern means having four numbers in front of the decimal point. If it is not enough, there are three numbers after the decimal point, and it is not enough to use 0. Output of the program:

1234.560

1234, 560

Similar, you can also control the format of the index form, for example:

Import java.text.decimalformat;

Public class decimalformat3 {

Public static void main (string args []) {

Decimalformat DF = New DecimalFormat ("0.000E0000");

System.out.println (DF.Format (1234.56));

}

}

Output:

1.235e0003

For percentage:

Import java.text.numberformat;

Public class decimalformat4 {

Public static void main (string args []) {

Numberformat nf = Numberformat.getPercentInstance ();

System.out.println (nf.format (0.47));

}

}

Output:

47%

At this point, you have seen several different techniques for formatting numbers. On the other hand, how to read and resolve a string containing formatted numbers? The parsing support is included in NumberFormat. E.g:

Import java.util.locale;

Import java.text.numberformat;

Import java.text.parseexception; public class decimalformat5 {

Public static void main (string args []) {

// Local format

Numberformat nf1 = Numberformat.getInstance ();

Object obj1 = null;

/ / Based on format analysis

Try {

Obj1 = nf1.parse ("1234, 56");

}

Catch (ParseException E1) {

System.err.println (E1);

}

System.out.println (OBJ1);

// German format

Numberformat nf2 = Numberformat.getInstance (locale.german);

Object obj2 = null;

/ / Based on format analysis

Try {

Obj2 = nf2.parse ("1234, 56");

}

Catch (Parsexception E2) {

System.err.Println (E2);

}

System.out.println (Obj2);

}

}

This example is divided into two parts, which are parsing a string: "1234, 56". The first part uses local format parsing, the second part uses German format parsing. When the program is running in the United States, the result is:

123456

1234.56

In other words, "1234, 56" is considered a huge integer "123456" in the United States and is considered a decimal "1234.56" in Germany.

3.4. DecimalFormat and NumberFormat

In the above example, DecimalFormat and NumberFormat were used. DecimalFormat is often used in well-format control, while NumberFormat is often used to specify different local areas. How to combine two classes?

The answer around this fact: DecimalFormat is a subclass of NumberFormat, which is specified as a specific area. Therefore, you can specify a region using NumberFormat.getInstance, and then force the structure to a DecimalFormat object. This technology mentioned in the document can be applied in most cases, but you need to enclose forced conversion with the try / catch block to prevent switching that does not work properly (probably uses a singular area under very unspeakable). Here is an example of this:

Import java.text.decimalformat;

Import java.text.numberformat;

Import java.util.locale;

Public class decimalformat6 {

Public static void main (string args []) {

Decimalformat DF = NULL;

/ / Get a NumberFormat object and

/ / Forced to convert to a DecimalFormat object

Try {

DF = (decimalformat) Numberformat.GetInstance (locale.german);

}

Catch (ClassCastException E) {

System.err.Println (e);

}

// Set the format mode

DF.ApplyPattern ("####. 00000");

// Format a Number

System.out.println (DF.Format (1234.56));

}

}

GetInstance () method gets the format, then call the ApplyPattern () method settings format mode, output: 1234, 56000

If you don't care about internationalization, you can use DecimalFormat directly.

Where v is the unprocessed double, scale is the requirements of demand, and returns a double that requires decimal digits.

Public Static Double Round (double v, int scale) {

IF (scale <0) {

Throw new IllegalargumentException

"The Scale Must Be a Positive Integer Or Zero");

}

BigDecimal B = New BigDecimal (Double.ToString (V));

BigDecimal One = New BigDecimal ("1");

Return B.divide (One, Scale, BigDecimal.Round_Half_up) .doubleValue ();

}

Package com.minht.sys.util; import java.text. *; import java.util. *; import java.math. *; / ** *

Title: format: open source, open *

description: Opeansource *

Copyright: Copyright (c) 2004 *

Company: 眀海 * @Author Haitang Ming * @version 1.0 * / public class Objectformat () {public objectformat () {} / ** * Output a given number in a given form * @Param D Double * @Param Pattern String * #: Indicates that there are numbers, output numbers, no empty, if output bit The number of digits is more than the number of digs, the extra length input * 0: There are numbers to output the number, not to supplement 0 * For the decimal, there are several # or 0, and several decimals are retained; * For example: "###. 00 "-> indicates the value of the output to keep two decimals, less than two digits, more than two rounds of all 5" ###. 0 # "-> indicate the value of the output can keep one or two digits The score; the integer is displayed as a decimal, one or two decimal display, more than two rounds of round; * "###" ---> Expressed as an integer, fractional part of the four rounds * ". ### "-> 12.234 shows it .234 *" #, ###. 0 # "-> Indicates an integer plus one", "; * @Param l locale * @return string * / public static string formatNumber (Double D, String Pattern, Locale L) {String S = ""; try {decimalformat nf = (decimalformat) NUMBERFORMAT.GETITINSTANCE (L); nf.applypattern (Pattern); s = nf.format (d);} catch (exception e) {E.PrintStackTrace (); debug.println ("formatNumber is error!");} return s;} / ** * Digital output by default Form * @Param D Double * @Param Pattern String * @Return String * / Public Static String FormatNumber (Double D, String Pattern) {Return FormatNumber (D, Pattern, Locale.getDefault ());} / ** * Format Currency * @Param D double * @Param Pattern String * "

/u00a4# ,:###.00 ": Displayed as ¥ 1,234,234.10 * @Param l locale * @Return string * / public static string formatcurrency (double d, string pattern, local l) {string s =" " Try {decimalformat nf = (decimalformat) NUMBERFORMAT.GETCURRENCYINSTANCE (L); NF.ApplyPattern (Pattern); s = nf.format (d);} catch (exception e) {E.PrintStackTrace (); debug.println (" FormatNumber is Error! ");} Return S;} / ** * Display currency * @Param D Double * @param pattern string * @param pattern string * @param pattern string * @RETURN STRING * / PUBLIC STATIC STRING FORMATCURRENCY (Double D, String Pattern) ) {RETURN FORMATCURENCY (D, Pattern, Locale.getDefault ());} / ** * Use the default mode to display currency: * For example: ¥ 12,345.46 defaults 2 decimal, rounded * @Param D double * @return string * / public static String formatCurrency (double d) {String s = ""; try {DecimalFormat nf = (DecimalFormat) NumberFormat.getCurrencyInstance (); s = nf.format (d);} catch (Exception e) {e.printStackTrace () Debug.println ("FormatNumber IS ERROR! ");} return s;} / ** * Format the 100 score in the specified area * @Param D * @Param Pattern:" ##, ##. 000% "-> Don't forget"% "* @ param l * @return * / public static String formatPercent (double d, String pattern, Locale l) {String s = ""; try {DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance (l); df.applyPattern (pattern); s = DF.FORMAT (D);} catCH (Exception E) {debug.print (e, "formatpercent is error!");} Return S;} / ** * Using the default area formatted 100 points * @Param D * @Param Pattern * @

转载请注明原文地址: http://www.9cbs.com/read-68193.html

New Post(0)