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
}
/**
* 將數(shù)據(jù)轉(zhuǎn)換為保留指定小數(shù)位數(shù)(0,1,2)格式的數(shù),四舍五入
*
*/
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());
}
/**
* 將數(shù)據(jù)轉(zhuǎn)換為保留指定小數(shù)位數(shù)(0,1,2)格式的數(shù)。向下取值:如 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);// 向下取值設(shè)置、
fm.format(num, sbf, new FieldPosition(java.text.NumberFormat.FRACTION_FIELD));
return Double.parseDouble(sbf.toString());
}
本文標(biāo)題:Lambda表達(dá)式mapToDouble.sum精度問(wèn)題
標(biāo)題網(wǎng)址:http://aaarwkj.com/article48/ggpjhp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、網(wǎng)站排名、域名注冊(cè)、ChatGPT、面包屑導(dǎo)航、
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)