java.text.DecimalFormat学习笔记

java.text.DecimalFormat学习笔记

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 DecimalFormat and DecimalFormatSymbols classes.


Patterns
You specify the formatting properties of DecimalFormat with a pattern String. The pattern determines what the formatted number looks like.
以下是DecimalFormat使用到的模板,这些模板的是递归解译的。

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 pound 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.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

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'..'//uFFFD' - specialCharacters
suffix     := '//u0000'..'//uFFFD' - specialCharacters
integer    := '#'* '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..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 (see ROUND_HALF_EVEN) for formatting.


see also
NumberFormat


例子:
import java.text.*;

public class Untitled1   {
  public static void main(String[] args) {

    //---------------------------------------------
    //定义一个数字格式化对象,格式化模板为".##",即保留2位小数.
    DecimalFormat a = new DecimalFormat(".##");
    String s= a.format(333.335);
    System.err.println(s);
    //说明:如果小数点后面不够2位小数,不会补零.参见Rounding小节
    //---------------------------------------------

    //-----------------------------------------------
    //可以在运行时刻用函数applyPattern(String)修改格式模板
    //保留2位小数,如果小数点后面不够2位小数会补零
    a.applyPattern(".00");
    s = a.format(333.3);
    System.err.println(s);
    //------------------------------------------------

    //------------------------------------------------
    //添加千分号
    a.applyPattern(".##/u2030");
    s = a.format(0.78934);
    System.err.println(s);//添加千位符后,小数会进三位并加上千位符
    //------------------------------------------------

    //------------------------------------------------
    //添加百分号
    a.applyPattern("#.##%");
    s = a.format(0.78645);
    System.err.println(s);
    //------------------------------------------------

   //------------------------------------------------
    //添加前、后修饰字符串,记得要用单引号括起来
    a.applyPattern("'这是我的钱$',###.###'美圆'");
    s = a.format(33333443.3333);
    System.err.println(s);
    //------------------------------------------------

     //------------------------------------------------
    //添加货币表示符号(不同的国家,添加的符号不一样
    a.applyPattern("/u00A4");
    s = a.format(34);
    System.err.println(s);
    //------------------------------------------------

    //-----------------------------------------------
    //定义正负数模板,记得要用分号隔开
     a.applyPattern("0.0;'@'-#.0");
     s = a.format(33);
     System.err.println(s);
     s = a.format(-33);
     System.err.println(s);
     //-----------------------------------------------
   
    //综合运用,正负数的不同前后缀
    String pattern="'my moneny'###,###.##'RMB';'ur money'###,###.##'US'";
    a.applyPattern(pattern);
    System.out.println(a.format(1223233.456));
  }
}

总结:
要生成一个DecimalFormat对象,一般只要通过NumberFormat类工厂的getInstance()来取得一个NumberFormat对象再将其转换成DecimalFormat对象,然后通过DecimalForat对象的applyPattern()来动态改变数据的现示格式模板,通过format()方法取得格式化后的数字。同时,DecimalFormat提供了许多的方法来返回格式化后的数字的某一部份,这些方法如:getNegativeSuffix()。这个类的难点主要是在模板的书写及理解上。其实主要的就是针对一个数字的正负形式来设定不同的格式显示。这里要特别注意的是使用在模板上的特殊字符代表有特殊的意义,如下表所示:
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

例如:如果模板中含有#,意思是指这个#号可代表一个或多个数字如果该位的数字是零的话则省略该位。另:注意“#,##0.0#;(#)”这个模板的意思是指数字的负数形式跟正数的一样。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值