diff --git a/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/service/homepage/HomepageSummaryServiceImpl.java b/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/service/homepage/HomepageSummaryServiceImpl.java index 4b8daff..4e8127a 100644 --- a/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/service/homepage/HomepageSummaryServiceImpl.java +++ b/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/service/homepage/HomepageSummaryServiceImpl.java @@ -29,6 +29,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; +import java.util.stream.IntStream; import static com.zteits.urbanops.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; @@ -323,17 +324,26 @@ public class HomepageSummaryServiceImpl implements HomepageSummaryService{ if (totalNum <= 0) { percents = Collections.singletonList(0); } else { - // 3. 先计算四舍五入占比 - List tempPercents = workOrderList.stream() - .map(vo -> (int) Math.round((vo.getTotal() * 100.0) / totalNum)) + List tempPercents = workOrderList.stream() + .map(vo -> { + double percent = (vo.getTotal() * 100.0) / totalNum; + int round = (int) Math.round(percent); + // 核心:只要 >0 的,至少给 1%,不允许出现 0% + return (round == 0 && vo.getTotal() > 0) ? 1 : round; + }) .collect(Collectors.toList()); - // 4. 核心:修正总和 = 100%(把差值补到最后一项) + // 校准总和 = 100% int sum = tempPercents.stream().mapToInt(Integer::intValue).sum(); - int diff = 100 - sum; + int diff = sum - 100; // 多出来的部分,从最大值减掉 + if (diff != 0 && !tempPercents.isEmpty()) { - int lastIndex = tempPercents.size() - 1; - tempPercents.set(lastIndex, tempPercents.get(lastIndex) + diff); + // 找出最大值的索引,把差值减掉(最合理,不会出现0) + OptionalInt maxIndex = IntStream.range(0, tempPercents.size()) + .reduce((i, j) -> tempPercents.get(i) > tempPercents.get(j) ? i : j); + if (maxIndex.isPresent()) { + tempPercents.set(maxIndex.getAsInt(), tempPercents.get(maxIndex.getAsInt()) - diff); + } } percents = tempPercents; }