一般情况下可以在实例化DecimalFormat对象时传递数字格式,也可以通过DecimalFormat类中的applyPattern()方法来实现数字格式化。
import java.text.*; //导入支持类java.text
public class DecimalFormatSimpleDemo {
//使用format()方法对数字进行格式化
static public void SimgleFormat(String pattern, double value){ //创建静态SimgleFormat成员方法
DecimalFormat myFormat = new DecimalFormat(pattern); //获取pattern中的数值并赋值给myFormat
String output = myFormat.format(value); //将数字进行格式化
System.out.println(value + " "+ pattern + " " + output); //输出原数值,输出的格式,输出格式化后的值
}
//使用applyPattern()方法对数字进行格式化
static public void UseApplyPatternMethodFormat(String pattern, double value){ //创建静态UseApplyPatternMethodFormat成员方法
DecimalFormat myFormat = new DecimalFormat(); //获取全部数值并赋值给myFormat
myFormat.applyPattern(pattern); //调用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); //在数字后加上单位
SimgleFormat("000000.000",123.78); //按照格式模板格式化数字,不存在的位以0显示
UseApplyPatternMethodFormat("#.###%",0.789); //调用静态UseApplyPatternMethodFormat()方法 ,将数字转换为百分数形式
UseApplyPatternMethodFormat("###.##",123456.789); //将小数点后格式化为两位
UseApplyPatternMethodFormat("0.00\u2030",0.789); //将数字转化为千分数形式
}
}
setGroupingSize设置数字分组和etGroupingUsed设置不允许数字分组
import java.text.DecimalFormat;
public class DecimalMethod {
public static void main(String[] args) {
DecimalFormat myFormat = new DecimalFormat();
myFormat.setGroupingSize(2); //设置数字分组个数为2
String output = myFormat.format(123456.789);
System.out.println("将数字以每两个数字分组:" + output);
myFormat.setGroupingUsed(false); //设置不允许数字分组
String output2 = myFormat.format(123456.789);
System.out.println("不允许数字分组" + output2);
}
}