Java DecimalFormat

来源:互联网 发布:青岛易亚网络骗局 编辑:程序博客网 时间:2024/06/05 22:50

  是NumberFormat 类的子类,主要的作用是用来格式化数字使用,当然,在格式化数字的时候要比直接使用NumberFormat 更加方便,因为可以直接指定按用户自定义方式进行格式化操作,与之前讲的SimpleDateFormat类似,如果要想进行自定义格式化操作,则必须指定格式化操作的模板。
下面给出如何定义模板:
这里写图片描述

一些例子:

import java.text.DecimalFormat;import java.util.Scanner;public class Main{    public void showFormat(String pattern,double value){        DecimalFormat df = null ;        df = new DecimalFormat(pattern) ;        String str = df.format(value) ;         System.out.println(pattern + " --> " + str) ;    }    public static void main(String[] args)    {        Main demo = new Main() ;        demo.showFormat("###,###.###",111222.34567) ;        demo.showFormat("000,000.000",11222.34567) ;        demo.showFormat("###,###.###¥",111222.34567) ;        demo.showFormat("000,000.000¥",11222.34567) ;        demo.showFormat("##.###%",0.345678) ;        demo.showFormat("00.###%",0.0345678) ;    }}

运行截图:
这里写图片描述

原创粉丝点击