Java.text.DecimalFormat Learning Notes

Source: Internet
Author: User
Tags locale

Java.text.DecimalFormat Learning Notes

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers into any locale,to obtain a numberform At in for a specific locale, including the default locale, call one of NumberFormat ' s factory methods, such as getinstance (). In general, don't call the DecimalFormat constructors directly since NumberFormat factory SSEs other than DecimalFormat. If you are need to customize the Format object, does something like this:

 numberformat f = numberformat.getinstance (loc);
 if (f instanceof decimalformat) {
     ((DecimalFormat) f). Setdecimalseparatoralwaysshown (TRUE);
 }
&NBSP
A decimalformat comprises a pattern and a set of symbols. The pattern may is set directly using Applypattern (), or indirectly using the API methods. The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods, the pattern and symbols are read from localized resourcebundles.

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) se Parators, and the decimal separator. If you are want to change formatting symbols, such as the decimal separator, your can use the DecimalFormatSymbols in Conjuncti On with the DecimalFormat class. These classes offer an great deal of flexibility in the formatting of numbers, but they can make your code more complex.
The text that follows uses examples that demonstrate the DecimalFormat and DecimalFormatSymbols.


Patterns
You are specify the formatting properties of DecimalFormat with a pattern String. The pattern determines what the formatted number looks like.
The following are the templates used by DecimalFormat, which are recursively interpreted.

DecimalFormat patterns have the following syntax:
Pattern:
Positivepattern
Positivepattern; Negativepattern
Positivepattern:
Prefixopt number suffixopt
Negativepattern:
Prefixopt number suffixopt
Prefix:
Any Unicode characters Except/ufffe,/UFFFF, and special characters
Suffix:
Any Unicode characters Except/ufffe,/UFFFF, and special characters
Number:
Integer exponentopt
Integer. Fraction exponentopt
Integer:
Minimuminteger
#
# Integer
#, Integer
Minimuminteger:
0
0 Minimuminteger
0, Minimuminteger
Fraction:
Minimumfractionopt optionalfractionopt
Minimumfraction:
0 minimumfractionopt
Optionalfraction:
# optionalfractionopt
Exponent:
E minimumexponent
Minimumexponent:
0 minimumexponentopt

A decimalformat pattern contains a positive and negative subpattern, for example, #,# #0; (#,# #0.00) ". Each subpattern has a prefix, numeric part, and suffix. The negative subpattern is optional; If absent, then the positive subpattern prefixed with the localized minus (sign "-' in code> most") is locales as th e negative subpattern. This is, "0.00" alone are equivalent to "0.00;-0.00". If there is a explicit negative subpattern, it serves only to specify the negative prefix and suffix; The number of digits, minimal digits, and other characteristics are the same as the positive. That means "#,# #0.0#;(#)" produces precisely the same behavior as "#,# #0.0#;(#,# #0.0#)".


Value Pattern Output explanation
123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit, the comma is a placeholder for the grouping SE Parator, and the period is a placeholder for the decimal separator.

123456.789 ###.## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only t Wo. The format method handles the-rounding up.

123.78 000000.000 000123.780 specifies leading and trailing zeros, because the 0 character is used Inste Ad of the pound sign (#).

12345.67 $###,###.### $12,345.67 The character in the "The" is the dollar sign ($). Note This it immediately precedes the leftmost digit in the formatted output.

12345.67/u00a5###,###.###¥12,345.67 the specifies the currency sign for Japanese yen (¥) with the Unicode V Alue 00a5.

Altering the formatting symbols

You can use the DecimalFormatSymbols class to change the symbols so appear in the formatted numbers produced by the form At method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others.
The next example demonstrates the DecimalFormatSymbols class by applying a strange format to a number. The unusual format is the result of the calls to the Setdecimalseparator, Setgroupingseparator, and Setgroupingsize method S.

DecimalFormatSymbols Unusualsymbols =
New DecimalFormatSymbols (Currentlocale);
Unusualsymbols.setdecimalseparator (' | ');
Unusualsymbols.setgroupingseparator (' ^ ');

String strange = "#,# #0. ###";
DecimalFormat Weirdformatter =
New DecimalFormat (Strange, unusualsymbols);
Weirdformatter.setgroupingsize (4);

String bizarre = Weirdformatter.format (12345.678);
System.out.println (bizarre);

When run, this example prints the number in a bizarre format:

1^2345|678

Number Format pattern Syntax

can design your own format patterns for numbers by following the rules specified by the following BNF:
Pattern: = Subpattern{;subpattern}
Subpattern: = {Prefix}integer{.fraction}{suffix}
Prefix: = '//u0000 ' ... ' Ufffd '-specialcharacters
Suffix: = '//u0000 ' ... ' Ufffd '-specialcharacters
Integer: = ' # ' * ' 0 ' * ' 0 '
Fraction: = ' 0 ' * ' # ' *

The notation used in the preceding diagram are explained in the following table:

Notation Description
x* 0 or more instances of X
(X | Y) either X or Y
X.. Y any character from X up to Y, inclusive
S-t characters in S, except those in T
{x} x is optional


Rounding
DecimalFormat uses Half-even rounding (= Round_half_even) for formatting.


Also
NumberFormat


Example:
Import java.text.*;

public class Untitled1 {
public static void Main (string[] args) {

//---------------------------------------------
Defines a number format object and formats the template as. # #, which preserves 2 decimal places.
DecimalFormat a = new DecimalFormat (". #");
String s= A.format (333.335);
System.err.println (s);
Note: If you do not have 2 decimal digits after the decimal point, you will not be 0. See rounding section
//---------------------------------------------

//-----------------------------------------------
You can modify a format template with function Applypattern (String) at run time
Keep 2 decimal digits, if not enough 2 decimal digits after the decimal point will complement 0
A.applypattern (". 00");
s = A.format (333.3);
System.err.println (s);
//------------------------------------------------

//------------------------------------------------
Add Chiphi
A.applypattern (". ##/u2030");
s = A.format (0.78934);
System.err.println (s);//After adding a thousand, the decimal number enters three digits and the thousand characters are added
//------------------------------------------------

//------------------------------------------------
Add percent sign
A.applypattern ("#.##%");
s = A.format (0.78645);
System.err.println (s);
//------------------------------------------------

//------------------------------------------------
Add pre and post decorated strings, remember to enclose them in single quotes
A.applypattern ("' This is my Money $ ', ###.### '");
s = A.format (33333443.3333);
System.err.println (s);
//------------------------------------------------

//------------------------------------------------
Add symbol for currency (different countries, added symbols not the same
A.applypattern ("/u00a4");
s = A.format (34);
System.err.println (s);
//------------------------------------------------

//-----------------------------------------------
Define positive negative number templates, remember to separate them with semicolons
A.applypattern ("0.0;") @ '-#.0 ');
s = A.format (33);
System.err.println (s);
s = A.format (-33);
System.err.println (s);
//-----------------------------------------------

Combined use, positive negative and different prefix
String pattern= "' My Moneny ' ###,###.## ' RMB '; ur money ' ###,###.## ' US ';
A.applypattern (pattern);
System.out.println (A.format (1223233.456));
}
}

Summarize:
To generate a DecimalFormat object, a NumberFormat object is typically obtained by getinstance () of the NumberFormat class factory and then converted to a DecimalFormat object. Then, the Decimalforat object's Applypattern () is used to dynamically change the present format template of the data, and the formatted number is obtained through the format () method. At the same time, DecimalFormat provides a number of ways to return a portion of the formatted number, such as: Getnegativesuffix (). The difficulty of this class is mainly in the writing and understanding of the template. In fact, the main thing is for a number of positive and negative form to set a different format display. It is important to note here that the special character represented on the template has special meaning, as shown in the following table:
Symbol Description
0 a digit
# a digit, zero shows as absent
. Placeholder for decimal separator
, placeholder for grouping separator
E separates Mantissa and exponent for exponential formats
; Separates formats
-Default Negative prefix
% multiply by and show as percentage
? Multiply by 1000 and show as per mille
¤currency sign; replaced by currency symbol; If doubled, replaced by international currency symbol; If present in a pattern, the monetary decimal separator is used instead of the decimal separator
X any other characters can is used in the prefix or suffix
' Used to quote special characters in a prefix or suffix

For example, if the template contains a #, it means that the # can represent one or more digits if the digit of that bit is 0, omit the bit. Also, note that "#,# #0.0#;(#)" This template means that the negative form of a number is the same as positive numbers.

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.