2016/04/22

Java 數值資料的 Format 格式化

在 Java 中,

輸出數值 123456789.234, 會得到 1.23456789234E8,

這時候, 可以利用『java.text.DecimalFormat』類別的『applyPattern』與『format』方法, 設定數值資料的格式化.

參考範例, 如下 :
 程式碼
public class HelloTomKuoWorld
{
    public static void main( String args[] )
    {
        double d1 = 123456789.234, d2 = 123456789.235, d3 = 123;
        
        DecimalFormat df = new DecimalFormat();
        
        System.out.println( "=== No Format ===" );
        System.out.println( "d1 = " + d1 );   // 1.23456789234E8
        System.out.println( "d2 = " + d2 );   // 1.23456789235E8
        System.out.println( "d3 = " + d3 );   // 123.0
        
        df.applyPattern( "0" );
        System.out.println( "=== 0 ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123456789
        System.out.println( "d2 = " + df.format(d2) );   // 123456789
        System.out.println( "d3 = " + df.format(d3) );   // 123
        
        df.applyPattern( "0.00" );
        System.out.println( "=== 0.00 ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123456789.23
        System.out.println( "d2 = " + df.format(d2) );   // 123456789.24
        System.out.println( "d3 = " + df.format(d3) );   // 123.00
        
        df.applyPattern( "0,000.00" );
        System.out.println( "=== 0,000.00 ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123,456,789.23
        System.out.println( "d2 = " + df.format(d2) );   // 123,456,789.24
        System.out.println( "d3 = " + df.format(d3) );   // 0,123.00
        
        df.applyPattern( "$0,000.00" );
        System.out.println( "=== $0,000.00 ===" );
        System.out.println( "d1 = " + df.format(d1) );   // $123,456,789.23
        System.out.println( "d2 = " + df.format(d2) );   // $123,456,789.24
        System.out.println( "d3 = " + df.format(d3) );   // $0,123.00
        
        df.applyPattern( "#" );
        System.out.println( "=== # ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123456789
        System.out.println( "d2 = " + df.format(d2) );   // 123456789
        System.out.println( "d3 = " + df.format(d3) );   // 123
        
        df.applyPattern( "#.##" );
        System.out.println( "=== #.## (Recommand) ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123456789.23
        System.out.println( "d2 = " + df.format(d2) );   // 123456789.24
        System.out.println( "d3 = " + df.format(d3) );   // 123
        
        df.applyPattern( "#,###.##" );
        System.out.println( "=== #,###.## ===" );
        System.out.println( "d1 = " + df.format(d1) );   // 123,456,789.23
        System.out.println( "d2 = " + df.format(d2) );   // 123,456,789.24
        System.out.println( "d3 = " + df.format(d3) );   // 123
    }
}