关于数字特殊字符 0 和 #的一些简单说明
#是一个特殊字符,用于数字部分(相当于占位符);它表示显示数字,但是最首位的0不予显示。
data:02222.20
pattern:",###.##"
result:2,222.2
#用于整数部分没有数位的限制,但是用于小数部分,却有“最多只能有多少位小数的意思”,多余的进行舍入。
data:2222.2222
pattern:",###.##"
result:2,222.22
0和#的用法是相近的,却又略有不同;不同之处在于: 0限制整数部分最少出现的位数;不足这个位数的,补0
data:22.26
pattern:"0,000.00"
result:0,022.26
0限制小数部分出现的位数;不足补0,多的舍入
data:22.26
pattern:"00.000"
result:22.260
pattern:"00.0"
result:22.3
可以根据需求将#和0搭配使用:
//保留两位小数
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.format(0.2));// 0.20
System.out.println(df.format(0.235));// 0.23
System.out.println(df.format(0.2351));// 0.24, 因为0.2351在0.23-0.24之间,距离0.24更近,所以输出0.24
System.out.println(df.format(42));// 42.00
System.out.println(df.format(0.29));// 0.29
System.out.println(df.format(999999999));// 999999999.00
System.out.println(df.format(0));// 0.00
BigDecimal b=new BigDecimal("9999999999");//10位
System.out.println(df.format(b));//9999999999.00
b=new BigDecimal("9999999999999");//13位
System.out.println(df.format(b));//
System.out.println("----------------------");
//保留两位小数并展示千分位符
DecimalFormat df1 = new DecimalFormat("##,##0.00");
System.out.println(df1.format(0.2));// 0.20
System.out.println(df1.format(0.235));// 0.24
System.out.println(df1.format(0.2351));// 0.24
System.out.println(df1.format(42));// 42.00
System.out.println(df1.format(0.29));// 0.29
System.out.println(df1.format(999999999));//999,999,999.00
System.out.println(df1.format(0));//0.00
b=new BigDecimal("9999999999");//10位 十亿
System.out.println(df1.format(b));//9,999,999,999.00
b=new BigDecimal("9999999999999");//13位
System.out.println(df1.format(b));//9,999,999,999,999.00
参考:/pro_kang/article/details/72240921