小数格式处理
2019-08-03 本文已影响0人
繁星追逐
主要记的是一个类 DecimalFormat ,
DecimalFormat是NumberFormat一个具体的子类,主要是格式化十进制数。它有各种各样的设计用于解析和格式化数字中的数字的特性区域设置,包括整数(123)、固定点编号(123.4)、科学记数法(1.23E4)、百分比(12%)和货币金额(123美元)等。
public static void main(String[] args) {
double a = 66.666666666666;
DecimalFormat format = new DecimalFormat("0.000000");
DecimalFormat format1 = new DecimalFormat();
format1.setMaximumFractionDigits(6);
System.out.println(format.format(a));
System.out.println(format1.format(a));
}
/**
* 获取格式化的double数的字符串
*
* 直接截取数值 不四舍五入
*
* @param num 需要被格式化的数
* @param sample 具体样式
* sample="0.00元"; 效果 : 2018.99元;
* sample="(万元)0.00"; 效果 : (万元)2018.99;
* sample="0.00¥"; 效果 : 2018.99¥;
* sample="¥0.00"; 效果 : ¥2018.99;
* sample="0.00%"; 效果 : 201899.00%; (自动乘以100)
* @return 格式化后的字符串
*/
public static String getDoubleFormat(double num, String sample){
DecimalFormat df=new DecimalFormat(sample);
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.DOWN);
return df.format(num);
}
//百分比 和 金额数值 打印
System.out.println(getDoubleFormat(0.99989,"0.00%"));//打印结果: 99.98%,自动乘以100
System.out.println(getDoubleFormat(1,"0.00%"));//打印结果: 100.00%,自动乘以100
System.out.println(getDoubleFormat(1.2577,"0.00 万元"));//打印结果: 1.25 万元
System.out.println(getDoubleFormat(12577,"0.00 元"));//打印结果: 12577.00 元
System.out.println(getDoubleFormat(12577,"¥ 0.00"));//打印结果: ¥ 12577.00
/**
* 获取带位分隔格式化的double数的字符串
* (带位分隔的就比较麻烦点了)
*
* 直接截取数值 不四舍五入
*
* @param num 需要被格式化的数
* @param groupingSize 需要几位整数分隔
* @param fractionDigits 需要保留几位小数
* @param suffix 后缀字符
* @return 格式化后的字符串
*/
public static String getGroupingFormat(double num,int groupingSize, int fractionDigits,String suffix){
DecimalFormat df=new DecimalFormat();
df.setMaximumFractionDigits(fractionDigits);
df.setMinimumFractionDigits(fractionDigits);
df.setGroupingSize(groupingSize);
df.setPositiveSuffix(suffix);
df.setNegativeSuffix(suffix);
df.setRoundingMode(RoundingMode.DOWN);
return df.format(num);
}
System.out.println(getGroupingFormat(12577,3,2," 元"));//打印结果: 12,577.00 元
System.out.println(getGroupingFormat(12577.998,3,2," 元"));//打印结果: 12,577.99 元
System.out.println(getGroupingFormat(177.998,3,2," ¥"));//打印结果: 177.99 ¥
//最多保留几位
df.setMaximumFractionDigits(6);
//最少保留几位, 可以是0 就是 取整数
df.setMinimumFractionDigits(2);