Java digital formatting processing method; internationalization

xiaoxiao2021-03-06  26

Sometimes we need to control the format of the output, how to use the Java class library to do this? For example, the number "1234.56" is output in "1234.560", "1, 234.56" format, where you can find an example: For example, numbers: 1, 1234.56 output in 1234.560 format

Decimalformat DF1 = New DecimalFormat ("####. 000");

Df1.setgroupingUsesed (false);

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

2, 1234.56 output at 123, 4.560

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

Df1.SetGroupingUsesed (True); //

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

3, 0.47 output with percentage

Numberformat nf = Numberformat.getPercentInstance ();

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

Output: 47%

4, output 1234.56 in local format

Numberformat nf1 = Numberformat.getInstance ();

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

If you run the program after running the program in the United States:

1,234.56

1.234, 56

-------------- If you want to know more carefully, the following article is available in ------------------- -

Translation: Cherami

Email: cherami@163.net

Original: http://developer.java.sun.com/developer/techtips/2000/tt0411.html

Sometimes we need to control the format of the output, how to use the Java class library to do this?

Maybe you don't care, but you need to care about your programs to be generally used worldwide, such as the following simple statement is dependent:

System.out.println (1234.56);

In the United States, "." Is a decimal point, but it is not necessarily in other places. How to deal with this?

Some packages in the Java.Text package can handle such problems. The following simple example uses those classes to solve the above problems:

Import java.text.numberformat;

Import java.util.locale;

Public class decimalformat1 {

Public static void main (string args []) {

// Get the local default format

Numberformat nf1 = Numberformat.getInstance ();

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

/ / Get the format of Germany

Numberformat nf2 =

Numberformat.getInstance (locale.german);

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

}

}

If you run the program after running the program in the United States:

1,234.56

1.234, 56

In other words, different habits are used in different places to represent numbers.

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 the 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 formatting 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.

There is also the last issue of formatting discussion. 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 to set the format mode, output:

1234, 56000

If you don't care about internationalization, you can use DecimalFormat directly directly ========================================= ================== We usually like to use SimpleDateFormat to do some of the dates and strings, which is called Format () and PARSE (), specific Use the program or the Java's API document, which is not described here. But us often forget, Java's internationalization is a happy thing. A problem with the following: String DateStr = "17 / Mar / 2003

11:30:51 "; SimpleDateFormat FRM = New SimpleDateFormat (" DD / MMM / YYYY HH: MM: SS "); Date Date = frm.parse (datedateformat frm1 = new SimpleDateFormat (" YYYY / MM / DD HH : mm: ss "); System.out.println (" Reformat: " frm1.format (date));

This will throw an exception Java.Text.Parsexception: unparseable date: "17 / mar / 2003 11:30:51", obviously the program cannot PARSE to "Mar" abbreviation. However, according to the document on the Java, there is no problem with the above programs. A typical runtime exception. Don't say to consider our environment. The environment written by the current program is Chinese WinXP, JDK1.4.2, IDEA 4.0, huh, we are Chinese, of course, I like to use Chinese environments. The question came out? Take a look at the code:

Date Date = new date (); SimpleDateFormat FRM1 = New SimpleDateFormat ("YYYY / MMM / DD HH: MM: SS"); System.out.Println ("Now:" frm1.format (date);

The output result is: now: 2004 / February / 24 11:57:00 See it, the default state, we use SimpleDateFormat to follow our current system LOCALE (please don't know how to translate in Chinese) It is also Chinese Locale, but the date string we have to analyze is in English, of course, I can't recognize it. OK, I know, we modified plus multiple locale, let SimpleDateFormat specified for local when constructed (Java is very stupid, we don't say how he knows?) Tell him that we have to deal with English. string

Locale locale = local.us; string datestr = "

17 / Mar / 2003

11:30:51 "; SimpleDateFormat FRM = New SimpleDateFormat (" DD / MMM / YYYY HH: MM: SS ", LOCALE); DATE = frm.parse (date); SimpleDateFormat FRM1 = New SimpleDateFormat (" YYYY / MM / DD HH: MM: SS ", LOCALE); System.Out.println (" Reformat: " frm1.format (date)); the program is normal ... The problem is mainly in our different internationalization Where you are not careful or easy to ignore, you are only a smile as a lesson.

The program is normal.

......

problem

Mainly in me

Weies

in difference

ring

Under the end

Correct

Some country

Aspect

Chemize

Place

Be above

Be careful or easy to ignore,

only

As a teach

Train

Everyone is smiling

.

----------------------------

Public Static Final BigDecimal TobigDecimal (String [] Patterns, String SRC) THROWS ESQSystemException {IF (Valueutils.isblankornull (src)) {Return NULL;}

BigDecimal value = null; int srcLength = src.length (); ParsePosition pos = new ParsePosition (0); DecimalFormat formatter = new DecimalFormat (); for (int i = 0; i

Formatter.ApplyPattern (Pattern); Number Num = Formatter.Parse (SRC, POS); if (Num! = null && srclength == pos.getIndex ()) {// 姺 惉 岟 (Num InstanceOf BigDecimal) {Value = (BigDecimal) Num;} else {double doublevalue = Num.doubleValue (); value = new bigdecimal (doublevalue);

Return Value;}}

Throw new esqsystemexception ("Parse Error =" SRC);

Public static final string [] decimal_pattern = {"0", "#, ## 0"}

Public static final string [] decimal_decimal_pattern = {"0.0", "#, ## 0.0"};

Public static final string [] decimal_pattern = {"0", "#, ## 0"}

Public static final string [] decimal_decimal_pattern = {"0.0", "#, ## 0.0"}; public static void main (string [] args) {

BigDecimal value = TobigDecimal (Decimal_Pattern, SRC);

}

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

New Post(0)