6.1. 数字格式化

6.1.1. DecimalFormat类

import java.text.DecimalFormat;
public class DecimalFormatSimpLE {
//  使用实例化对象时设置格式化模式
    static public void SimgleFormat(String pattern,double value) {
//      实例化DecimalFormat对象
        DecimalFormat myFormat = new DecimalFormat(pattern);
        String output = myFormat.format(value);     //将数字进行格式化
        System.out.println(value+" ---->"+ pattern+"====>"+output);


    }
    static public void UseApplyPattemMethodFormat(String pattern,double value) {
//      实例化DecimalFormat对象
        DecimalFormat myFormat = new DecimalFormat();
//      调用applyPattern()方法设置格式化模板
        myFormat.applyPattern(pattern);
        System.out.println(value + " " + pattern + " " + myFormat.format(value));

    }
    public static void main(String[] args) {
        SimgleFormat("###,###.###", 123456.789);    //调用静态SimgleFormat()方法
        SimgleFormat("000000000.###kg", 123456.789); //在数字后加上单位
//      按照格式模板格式化数字,不存在的位以0显示
        SimgleFormat("000000.000", 123.78);

//      调用静态UseApplyPattemMethodFormatF()方法
        UseApplyPattemMethodFormat("#.###%", 0.789);    //将数字转换为百分数形式
//      将小数点后格式化为两位
        UseApplyPattemMethodFormat("###.##", 123456.789);
//      将数字转化为千分数形式
        UseApplyPattemMethodFormat("0.00\u2030", 0.789);

    }
}

/*输出信息
123456.789 ---->###,###.###====>123,456.789
123456.789 ---->000000000.###kg====>000123456.789kg
123.78 ---->000000.000====>000123.780
0.789 #.###% 78.9%
123456.789 ###.## 123456.79
0.789 0.00‰ 789.00‰

 */

6.1.2. DecimalFormat类中的分组方法

使用setGroupingSize() 与setGroupingUsed() 方法设置数字格式
import java.text.DecimalFormat;

public class DecimalFormation {
    public static void main(String[] args) {
//      实例化DecimalFormat对象
        DecimalFormat myFormat = new DecimalFormat();
//      设置将数字分组为2
        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);
    }


}

/*输出内容
将数字以每两个数字分组 12,34,56.789
不允许数字分组 123456.789
 */