【Java常用类库】_NumberFormat

【Java常用类库】_NumberFormat

import java.text.* ;
public class NumberFormatDemo01{
    public static void main(String args[]){
        NumberFormat nf = null ;        // 声明一个NumberFormat对象
        nf = NumberFormat.getInstance() ;    // 得到默认的数字格式化显示
        System.out.println("格式化之后的数字:" + nf.format(10000000)) ;
        System.out.println("格式化之后的数字:" + nf.format(1000.345)) ;
    }
};


输出:

格式化之后的数字:10,000,000
格式化之后的数字:1,000.345



实例化模板:



import java.text.* ;
class FormatDemo{
    public void format1(String pattern,double value){    // 此方法专门用于完成数字的格式化显示
        DecimalFormat df = null ;            // 声明一个DecimalFormat类的对象
        df = new DecimalFormat(pattern) ;    // 实例化对象,传入模板
        String str = df.format(value) ;        // 格式化数字
        System.out.println("使用" + pattern
            + "格式化数字" + value + ":" + str) ;
    }
};
public class NumberFormatDemo02{
    public static void main(String args[]){
        FormatDemo demo = new FormatDemo() ;    // 格式化对象的类
        demo.format1("###,###.###",111222.34567) ;
        demo.format1("000,000.000",11222.34567) ;
        demo.format1("###,###.###¥",111222.34567) ;
        demo.format1("000,000.000¥",11222.34567) ;
        demo.format1("##.###%",0.345678) ;
        demo.format1("00.###%",0.0345678) ;
        demo.format1("###.###\u2030",0.345678) ;
    }
};

输出:

使用###,###.###格式化数字111222.34567:111,222.346
使用000,000.000格式化数字11222.34567:011,222.346
使用###,###.###¥格式化数字111222.34567:111,222.346¥
使用000,000.000¥格式化数字11222.34567:011,222.346¥
使用##.###%格式化数字0.345678:34.568%
使用00.###%格式化数字0.0345678:03.457%
使用###.###‰格式化数字0.345678:345.678‰


你可能感兴趣的:(【Java常用类库】_NumberFormat)