数字格式化

 

 

 

 1 package test;
 2 
 3 import java.text.DecimalFormat;
 4 
 5 public class DecimalFormatSimpleDemo {
 6     
 7             //使用实例化对象设置格式化模式
 8             static public void SingleFormat(String pattern,double value){
 9                 //实例化DecimalFormat对象
10                 DecimalFormat myFormat = new DecimalFormat(pattern);
11                 String output = myFormat.format(value);
12                 System.out.println(value+" "+pattern+" "+output);
13             }
14             //使用applyFormat()方法对数字进行格式化
15             static public void UseApplyFormatMethodFormat(String pattern,double value){
16                 DecimalFormat myFormat = new DecimalFormat();//实例化DecimalFormat对象
17                 myFormat.applyPattern(pattern);
18                 System.out.println(value+" "+pattern+" "+myFormat.format(value));
19             }
20                     
21             public static void main(String[] args) {
22                 SingleFormat("###,###.###",123456.789);//调用静态SingleFormat()方法
23                 SingleFormat("00000000.###kg",123456.789);//在数字后面加上单位
24                 //按照格式模板格式化数字,不存在的位以0显示
25                 SingleFormat("000000.000", 123.78);
26                 //调用静态UseApplyFormatMethodFormat()方法
27                 UseApplyFormatMethodFormat("###.##%", 0.789);//将数字转换成百分数形式
28                 //将小数点后格式化为两位
29                 UseApplyFormatMethodFormat("###.##", 123456.789);
30                 //将数字转化为千分数形式
31                 UseApplyFormatMethodFormat("0.00\u2030", 0.789);
32                 
33             }
34     
35     
36 
37 }

 

package test;

import java.text.DecimalFormat;

public class DecimalMethod {

    public static void main(String[] args) {
        DecimalFormat myFormat = new DecimalFormat();
        myFormat.setGroupingSize(2);//将数字以每两个数字分组(整数部分)
        String output = myFormat.format(123456.789);
        System.out.println("将数字以每两个数字分组:"+output);
        myFormat.setGroupingUsed(false);//设置不允许数字进行分组
        String output2 = myFormat.format(123456.789);
        System.out.println("不允许数字分组"+output2);
    }

}

 

posted @ 2018-06-27 10:07  xiaotao520  阅读(348)  评论(0编辑  收藏  举报