public static void main(String[] args) {
List<Double> doubles = Arrays.asList(new Double(3.3), new Double(3.3), new Double(3.3));
double sum = doubles.stream().mapToDouble(Double::doubleValue).sum();
System.out.println(sum);// 9.899999999999999
System.out.println(formatDigit(sum,2));// 9.9
System.out.println(formatDigit_down(sum, 2)); // 9.89
List<Double> doubles1 = Arrays.asList(new Double(1.1), new Double(1.1), new Double(1.1));
double sum1 = doubles1.stream().mapToDouble(Double::doubleValue).sum();
System.out.println(sum1);// 3.3000000000000003
System.out.println(formatDigit(sum1,2));// 3.3
System.out.println(formatDigit_down(sum1, 2));// 3.3
}
/**
* 将数据转换为保留指定小数位数(0,1,2)格式的数,四舍五入
*
*/
public static double formatDigit(double num, int decimalPlace) {
DecimalFormat fm = null;
switch (decimalPlace) {
case 0:
fm = new DecimalFormat("##");
break;
case 1:
fm = new DecimalFormat("##.#");
break;
case 2:
fm = new DecimalFormat("##.##");
break;
case 3:
fm = new DecimalFormat("##.###");
break;
case 4:
fm = new DecimalFormat("##.####");
break;
default:
break;
}
if (fm == null) {
return num;
}
StringBuffer sbf = new StringBuffer();
fm.format(num, sbf, new FieldPosition(java.text.NumberFormat.FRACTION_FIELD));
return Double.parseDouble(sbf.toString());
}
/**
* 将数据转换为保留指定小数位数(0,1,2)格式的数。向下取值:如 5.567 -> 5.56 -5.567 -> -5.56
*/
public static double formatDigit_down(double num, int decimalPlace) {
DecimalFormat fm = null;
switch (decimalPlace) {
case 0:
fm = new DecimalFormat("##");
break;
case 1:
fm = new DecimalFormat("##.#");
break;
case 2:
fm = new DecimalFormat("##.##");
break;
case 3:
fm = new DecimalFormat("##.###");
break;
case 4:
fm = new DecimalFormat("##.####");
break;
default:
break;
}
if (fm == null) {
return num;
}
StringBuffer sbf = new StringBuffer();
fm.setRoundingMode(RoundingMode.DOWN);// 向下取值设置、
fm.format(num, sbf, new FieldPosition(java.text.NumberFormat.FRACTION_FIELD));
return Double.parseDouble(sbf.toString());
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。