1. 程式人生 > >用 DecimalFormat 格式化數字

用 DecimalFormat 格式化數字

引言
Java中對浮點數的輸出表示
在Java中浮點數包括基本型float、double,以及物件包裝型別的Float和Double,對於這些浮點數的輸出,不管是顯式地還是隱式地呼叫toString()得到它的表示字串,輸出格式都是按照如下規則進行的
如果絕對值大於0.001、小於10000000,那麼就以常規的小數形式表示。    
如果在上述範圍之外,則使用科學計數法表示。即類似於1.234E8的形式。

可以使用 java.text.DecimalFormat及其父類NumberFormat格式化數字
本例只淺述DecimalFormat的使用。

Pattern
0 - 如果對應位置上沒有數字,則用零代替
# - 如果對應位置上沒有數字,則保持原樣(不用補);如果最前、後為0,則保持為空。
正負數模板用分號(;)分割

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'* '#'*

DEMO
value
123456.789

pattern
,###.###

output
123,456.789

Explanation
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.
井號(#)表示一位數字,逗號是用於分組分隔符的佔位符,點是小數點的佔位符。 
如果小數點的右面,值有三位,但是式樣只有兩位。format方法通過四捨五入處理。

value
123.78

pattern
000000.000

output
000123.780

Explanation
The pattern specifies leading and trailing zeros, 
because the 0 character is used instead of the pound sign (#). 

應用例項 1:
/* * Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved. */
import java.util.*; 
import java.text.*; 
public class DecimalFormatDemo { 
 static public void customFormat(String pattern, double value ) { 
  DecimalFormat myFormatter = new DecimalFormat(pattern); 
  String output = myFormatter.format(value); 
  System.out.println(value + " " + pattern + " " + output); 
 } 
 static public void localizedFormat(String pattern, double value, Locale loc ) { 
  NumberFormat nf = NumberFormat.getNumberInstance(loc); 
  DecimalFormat df = (DecimalFormat)nf; 
  df.applyPattern(pattern); 
  String output = df.format(value); 
  System.out.println(pattern + " " + output + " " + loc.toString()); 
 } 
 static public void main(String[] args) { 
  customFormat("###,###.###", 123456.789); 
  customFormat("###.##", 123456.789); 
  customFormat("000000.000", 123.78); 
  customFormat("$###,###.###", 12345.67); 
  customFormat("\u00a5###,###.###", 12345.67); 
  Locale currentLocale = new Locale("en", "US"); 
  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); 
  Locale[] locales = { new Locale("en", "US"), 
         new Locale("de", "DE"), 
         new Locale("fr", "FR") }; 
  for (int i = 0; i < locales.length; i++) { 
   localizedFormat("###,###.###", 123456.789, locales); 
  } 
 } 


應用例項 2:
參見:Mark Leung的學習總結
     http://blog.csdn.net/marcoleung/archive/2004/11/11/176514.aspx
public class test
{
    public test()
    {
    //---------------------------------------------
    //定義一個數字格式化物件,格式化模板為".##",即保留2位小數.
    DecimalFormat a = new DecimalFormat("##.##");
    String s= a.format(03.03035);
    System.err.println(s);
    String s= a.format(03.30);
    System.err.println(s);
    String s= a.format(03.335);
    System.err.println(s);
    String s= a.format(03.3);
    System.err.println(s);
    //說明:如果小數點後面不夠2位小數,不會補零.參見Rounding小節
    //---------------------------------------------

    //-----------------------------------------------
    //可以在執行時刻用函式applyPattern(String)修改格式模板
    //保留2位小數,如果小數點後面不夠2位小數會補零
    a.applyPattern("00.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(2533333443.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));
  }


    public static void main(String[] args)
    {
        test test1 = new test();
    }
}