java.math.RoundingMode

本文详细解读了Java数学库中的RoundingMode舍入模式,包括HALF_UP和UP两种模式的原理及应用示例,提供深入理解Java数值处理的基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.math.RoundingMode
http://blog.youkuaiyun.com/alanzyy/article/details/8465098
RoundingMode.HALF_UP
向最接近数字方向舍入的舍入模式,如果与两个相邻数字的距离相等,则向上舍入。如果被舍弃部分 >= 0.5,则舍入行为同 RoundingMode.UP;否则舍入行为同RoundingMode.DOWN。注意,此舍入模式就是通常学校里讲的四舍五入。
示例:
输入数字 使用 HALF_UP 舍入模式
将输入数字舍入为一位数
5.5 6
2.5 3
1.6 2
1.1 1
1.0 1
-1.0 -1
-1.1 -1
-1.6 -2
-2.5 -3
-5.5 -6


RoundingMode.UP
public static final RoundingMode UP
远离零方向舍入的舍入模式。始终对非零舍弃部分前面的数字加 1。注意,此舍入模式始终不会减少计算值的绝对值。
示例:
输入数字 使用 UP 舍入模式
将输入数字舍入为一位数
5.5 6
2.5 3
1.6 2
1.1 2
1.0 1
-1.0 -1
-1.1 -2
-1.6 -2
-2.5 -3
-5.5 -6
package com.xymzsfxy.backend.service; import com.xymzsfxy.backend.entity.History; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDateTime; import java.util.List; import java.util.Random; @Component public class MyJobService { @Autowired private HistoryService historyService; @Scheduled(cron = "*/5 * * * * *") public void updatePriceHistory() { System.out.println("开始更新啦"); List<History> priceHistories = historyService.findAll(); Random random = new Random(); priceHistories.forEach(history -> { BigDecimal newPrice = new BigDecimal(random.nextDouble() * 1000); history.setPrice(newPrice); history.setLogisticsCost(new BigDecimal(random.nextDouble() * 100)); history.setTotalCost(history.getPrice().add(history.getLogisticsCost())); history.setRating(new BigDecimal(random.nextDouble() * 5).setScale(1, RoundingMode.HALF_UP)); history.setCrawlTime(LocalDateTime.now()); // 比较新价格与最高价和最低价 BigDecimal currentMaxPrice = history.getMaxPrice(); BigDecimal currentMinPrice = history.getMinPrice(); if (currentMaxPrice == null || newPrice.compareTo(currentMaxPrice) > 0) { history.setMaxPrice(newPrice); System.out.println(newPrice); } if (currentMinPrice == null || newPrice.compareTo(currentMinPrice) < 0) { history.setMinPrice(newPrice); System.out.println(newPrice); } String[] sources = {"天猫", "淘宝"}; int index = random.nextInt(sources.length); history.setSource(sources[index]); }); historyService.batchUpdate(priceHistories); // 批量更新 } }数据只保留两位小数,修改之后解读一下代码,currentMinPrice == null || newPrice.compareTo(currentMinPrice) < 0 目前currentMinPrice 和最大价格都初始化为0不是null给出修改后的完整代码
03-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值