涉及小数的计算,最好都统一用BigDecimal来处理,保证运算精度
在构建BigDecimal时,用字符串做参数,其它方式会有精度问题
BigDecimal bd= new BigDecimal("123456789.11112233");
//方法
add()
subtract()
multiply()
divide()
//格式化
NumberFormat nf = NumberFormat.getNumberInstance() ;
nf.setMaximumFractionDigits(2) ;
nf.setMinimumFractionDigits(2);
nf.format(bd);
//大小比较
if(a.compareTo(b) == -1){
//<
}else if(a.compareTo(b) == 0){
//==
}else if(a.compareTo(b) == 1){
//>
}
//小数四舍五入模式
BigDecimal b = new BigDecimal("123.6779");
System.out.println(b.setScale(2, BigDecimal.ROUND_DOWN));//向下舍入 123.67
手机号13777777777,如果是为Double类型接收,就会自动转为科学计数法,可这样处理
一般是Double转String,方法一般有两种:
1.利用String.format()
saleUnilateImport.setPhone(String.format("%.4f", row.getCell(1).getNumericCellValue()));//15145117218.0000保留4位小数
String.format("%.0f", row.getCell(0).getNumericCellValue())//15145117218,取整!
2.利用DecimalFormat类
DecimalFormat df = new DecimalFormat("#");//转换成整型
saleUnilateImport.setPhone(df.format(row.getCell(1).getNumericCellValue()));
3.利用DecimalFormat类
DecimalFormat df = new DecimalFormat("#,##0.00");//保留两位小数且不用科学计数法saleUnilateImport.setPhone(df.format(row.getCell(1).getNumericCellValue()));
格式化类,
DecimalFormat格式化double
SimpleDateFormat格式化Date
DecimalFormat df = new DecimalFormat( "#,##0.00 ");
//保留两位小数且不用科学计数法,并使用千分位
String value = df.format(d);
不用科学计数法
NumberFormat n = NumberFormat.getInstance();
n.setGroupingUsed(false);
n.setMaximumFractionDigits(100);
System.out.println(n.format(0.0000001));//0.0000001
在构建BigDecimal时,用字符串做参数,其它方式会有精度问题
BigDecimal bd= new BigDecimal("123456789.11112233");
//方法
add()
subtract()
multiply()
divide()
//格式化
NumberFormat nf = NumberFormat.getNumberInstance() ;
nf.setMaximumFractionDigits(2) ;
nf.setMinimumFractionDigits(2);
nf.format(bd);
//大小比较
if(a.compareTo(b) == -1){
//<
}else if(a.compareTo(b) == 0){
//==
}else if(a.compareTo(b) == 1){
//>
}
//小数四舍五入模式
BigDecimal b = new BigDecimal("123.6779");
System.out.println(b.setScale(2, BigDecimal.ROUND_DOWN));//向下舍入 123.67
手机号13777777777,如果是为Double类型接收,就会自动转为科学计数法,可这样处理
一般是Double转String,方法一般有两种:
1.利用String.format()
saleUnilateImport.setPhone(String.format("%.4f", row.getCell(1).getNumericCellValue()));//15145117218.0000保留4位小数
String.format("%.0f", row.getCell(0).getNumericCellValue())//15145117218,取整!
2.利用DecimalFormat类
DecimalFormat df = new DecimalFormat("#");//转换成整型
saleUnilateImport.setPhone(df.format(row.getCell(1).getNumericCellValue()));
3.利用DecimalFormat类
DecimalFormat df = new DecimalFormat("#,##0.00");//保留两位小数且不用科学计数法saleUnilateImport.setPhone(df.format(row.getCell(1).getNumericCellValue()));
格式化类,
DecimalFormat格式化double
SimpleDateFormat格式化Date
DecimalFormat df = new DecimalFormat( "#,##0.00 ");
//保留两位小数且不用科学计数法,并使用千分位
String value = df.format(d);
不用科学计数法
NumberFormat n = NumberFormat.getInstance();
n.setGroupingUsed(false);
n.setMaximumFractionDigits(100);
System.out.println(n.format(0.0000001));//0.0000001