Java BigDecimal: 计算字符串列表的总和并保留两位小数
List<String> energyList = new ArrayList<>(); // Assuming energyList is populated with strings
BigDecimal sum = BigDecimal.ZERO; for (String energy : energyList) { BigDecimal energyValue = new BigDecimal(energy); sum = sum.add(energyValue); }
sum = sum.setScale(2, RoundingMode.HALF_UP); System.out.println(sum); // Prints the sum with two decimal places
原文地址: https://www.cveoy.top/t/topic/pKaZ 著作权归作者所有。请勿转载和采集!