保留小数点(四舍五入)java

public class Decimal {
public static void main(String[] args) {
	double d=6.666;
	//1、只是用来打印输出,这种最方便,会自动四舍五入。%.2f表示保留2位小数,同理%.1f,%.3f
	System.out.println(String.format("%.2f", d));
	
	//2、使用DecimalFormat类
	DecimalFormat df=new DecimalFormat("#.00");
	System.out.println(df.format(d));
	
	//3、不使用任何函数或类,手动转换
	double tmp=(int)(d*100+0.5);
	double res=tmp/100;
	System.out.println(res);
}
}
明白了,你现在的需求是: > ✅ **将高频淬火工序的工时从“秒”转为“分钟”,并保留小数点后两位,进行四舍五入。** --- ## ✅ 实现方式 在 Java 中,要实现 **保留小数点后两位 + 四舍五入**,推荐使用 `Math.round()` 或 `BigDecimal`。 我们选择 `BigDecimal`,因为它在精度要求高的场景下更可靠。 --- ## ✅ 优化后的 `getMillingTime()` 方法(含四舍五入) ```java import java.math.BigDecimal; import java.math.RoundingMode; public class MillingTimeUtils { public static float getMillingTime(String processType, float diameter, float length) { AbsMillingWorkTime process = MillingProcessFactory.getProcess(processType); if (process == null) { System.err.println("不支持的工序类型: " + processType); return 0f; } float rawTime = process.getBaseWorkTime(diameter, length); // 只对“高频淬火”做“秒”转“分钟” if ("高频淬火".equals(processType)) { // 转换为分钟,并保留两位小数四舍五入 BigDecimal timeInMinutes = new BigDecimal(rawTime / 60f) .setScale(2, RoundingMode.HALF_UP); return timeInMinutes.floatValue(); } // 其他工序直接返回(默认是分钟) return rawTime; } // 示例调用 public static void main(String[] args) { float diameter = 55f; float length = 150f; float time = getMillingTime("高频淬火", diameter, length); System.out.printf("工时:%.2f 分钟%n", time); // 输出:工时:2.05 分钟(假设原始值是 123f 秒) } } ``` --- ## ✅ 示例:转换逻辑说明 | 秒数 | 转换为分钟 | 保留2位小数四舍五入) | |------|------------|--------------------------| | 90 | 1.5 | 1.50 | | 123 | 2.05 | 2.05 | | 125 | 2.0833... | 2.08 | | 127 | 2.1166... | 2.12 | --- ## ✅ 使用说明 - ✅ `BigDecimal`:更精确,适合金融、工业、工时计算等场景 - ✅ `setScale(2, RoundingMode.HALF_UP)`:保留 2 位小数四舍五入 - ✅ `RoundingMode.HALF_UP`:Java 中标准的四舍五入方式 - ✅ 不影响其他工序单位(只有高频淬火需要处理) --- ## ✅ 可选封装:格式化输出(如 `String`) 如果你想返回 `String` 格式,方便显示: ```java public static String getMillingTimeFormatted(String processType, float diameter, float length) { float minutes = getMillingTime(processType, diameter, length); return String.format("%.2f", minutes); } ``` 这样你可以直接用于界面显示或日志输出。 --- ## ✅ 总结 | 需求 | 实现方式 | |------|-----------| | 高频淬火转分钟 | `seconds / 60f` | | 保留2位小数 | `BigDecimal.setScale(2, RoundingMode.HALF_UP)` | | 四舍五入 | `RoundingMode.HALF_UP` | | 不影响其他工序 | 仅对 `"高频淬火"` 做特殊处理 | --- ✅ **最终推荐做法**: > 在 `getMillingTime()` 中判断工序类型,如果是“高频淬火”,就做“秒转分钟”,并用 `BigDecimal` 保留2位小数四舍五入,确保精度准确。 --- 如果你希望我帮你: - ✅ 生成完整工具类(含日志、异常处理) - ✅ 生成带工厂模式的完整结构 - ✅ 或者帮你生成 `JSON` 配置文件来控制哪些工序需要“秒转分钟” 也可以继续告诉我,我可以为你定制完整解决方案 😊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值