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 in any locale, To obtain a NumberFormat for a specific locale, including the default locale, call one of NumberFormat's . factory methods, such as getInstance () In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat If you need to customize the format object, do something like this.:
NumberFormat f = NumberFormat.getInstance (loc); if (f instanceof DecimalFormat) {((DecimalFormat) f) .setDecimalSeparatorAlwaysShown (true);} A DecimalFormat comprises a pattern and a set of symbols The pattern may be 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 you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. If you want to change formatting symbols, such as the decimal separator, you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. These classes offer a 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 DecimaLMat and DecimalFormatsymbols Classes.
Patternsyou Specify The formatting Properties of DeciMAlFormat with a pattern string. The pattern determines what the formatted Number Looks Like. The following is a template used by DecimalFormat, which is recursive interpresed. 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.00; (#, ## 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 (code> '-' in most locales) is used as the negative subpattern That is, "0.00" alone is equivalent to "0.00; -0.00" If there is an explicit negative. subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are all the same as the positive pattern that means that "#, ## 0.0 #; (#)". produces precisely The Same Behavior AS "#, ## 0.0 #; (#, ## 0.0 #)". Value Pattern Output Explanation 123456.789 ###, ###. ### 123,456.789 The point sign (#) Denotes a Digit, The Comma is a placeholder for the grouping separator, 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 two. The format method handles this by rounding up. 123.78 000000.000 000123.780 The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#). 12345.67 $ ###, ###. ### $ 12,345.67 The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in The formatted output.
12345.67 /u00a5########## ¥ 12,345.67 The pattern specifies the currency sign for japanese yen (¥) with the Unicode Value 00a5.
Altering the formatting symbols
You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format 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 methods.DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols (currentLocale); unusualSymbols.setDecimalSeparator ( '|');. unusualSymbols. SetGroupingseParetor ('^');
String strange = "#, ## 0. ###"; decimalformat weird = 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
You can design your own format patterns for numbers by following the rules specified by the following BNF diagram: pattern: = subpattern {; subpattern} subpattern: = {prefix} integer {.fraction} {suffix} prefix: = '// u0000' .. '// uffd' - Specialcharacterssuffix: = '//u0000'..'///ufffd' - Specialcharactersinteger: = '#' * '0' * '0'fraction: =' 0 '*' # '*
The Notation Used in The Preceding Diagram Is Explained in The Following Table:
NOTATION Description X * 0 or More Instances of X (X | Y) Either X or Y X Up To Y, Inclusive S - T Characters In s, Except Those In T {x} x is optionALROUNDITECIMALMAT USES Half-Even runking (see round_half_even) for formatting.
See AlsonumberFormat
Example: Import java.text. *;
Public class unhatted1 {public static void main (string [] args) {
// -------------------------------- // Definition A digital formatted object, formatting template is ". ##", that is, 2 digits. Decimalformat a = new decimalformat (". ##"); string s = a.Format (333.335); system.rr.println (s); // Description: If the decimal point is not enough 2 decimal, do not make up. See runking section // ------------------------ ---------------------
/ / ----------------------------------- / / Can modify the format template / / reserved 2 digits in the run time, if the decimal point is not enough 2 decimals will make up zero A.ApplyPattern (". 00"); s = a.Format (333.3); System.err.println (s); // --------------------------------------- ---------
/ / -------------------------------------------------------------------------------------------- // Add a thousand semicaral a.applypattern (". ## / u2030"); s = a.Format (0.78934); system.err.println (s); // After adding thousands, decimal will enter three And plus thousands // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------
/ / -------------------------------------------------------------------------------------------- // Add a percentage A.ApplyPattern ("#. ##%"); s = a.Format (0.78645); system.err.println (s); // ----------- -------------------------------------
/ / -------------------------------------------------------------------------------------------- // Before adding, the post-decoration string, remember to enclose a.applypattern ("'this is my money $', ####### = a.format ( 33333443.3333); System.err.Println (s); // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------
/ / -------------------------------------------------------------------------------------------- // Add a currency representation symbol (different countries, the added symbol is different A.ApplyPattern ("/ u00A4"); s = a.mmat (34); system.err.println (s); // ------ ------------------------------------------ // ---- ------------------------------------------ / / Define Positive Negative Template I remember to separate A.ApplyPattern ("0.0; '@' - #. 0"); s = a.rr.println (s); s); s = a.FORMAT 33); System.err.Println (s); // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------- // Comprehensive application, different front and backfire string pattern = "'my monny' ###, ###. ## 'Rmb'; 'UR Money' # ##, ###. ## 'us' "; A.ApplyPattern (Pattern); System.out.println (A.Format (1223233.456));}}
Summary: To generate a DecimalFormat object, generally simply get a NumberFormat object through the NumberFormat class factory to get a NumberFormat object to a DecimalFormat object, and then dynamically change the data of the status format template by the decimalforat object. The format () method obtains the formatted number. At the same time, DecimalFormat provides a number of methods to return some part of the formatted numbers, such as getnegativeSuffix (). The difficulty of this class is mainly on the writing and understanding of the template. In fact, the main thing is to set different formats for a number of positive and negative forms. It is important to pay special attention to the special character representative of special characters on the template, 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 100 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 be used in the prefix or suffix 'used to quote special characters in a prefix or suffix, for example: if the template contains a #, is meant the # The number can represent one or more numbers If the number of the bit is zero, the bit is omitted. Another: Note "#, ## 0.0 #; (#)" This template means that the negative form of the number is the same as the positive number.