You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中Math.round()对16.275保留两位小数异常的原因及解决办法

Math.round处理16.275保留两位小数得到16.27的问题解决

问题原因

这是double类型的二进制浮点数精度限制导致的:16.275无法被二进制浮点数精确存储,实际在内存中它是一个略小于16.275的近似值(约等于16.274999999999998)。当执行x*100.0时,结果约为1627.4999999999998,Math.round()会将这个值舍入为1627,最终除以100后得到16.27。

解决方案

方法1:使用BigDecimal精确计算

BigDecimal专为精确处理十进制数值设计,能避免浮点数精度丢失问题,是最可靠的方案:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        // 用字符串构造BigDecimal,避免直接传入double带来的精度问题
        BigDecimal num = new BigDecimal("16.275");
        // 保留2位小数,采用标准四舍五入规则
        BigDecimal roundedNum = num.setScale(2, RoundingMode.HALF_UP);
        System.out.println(roundedNum); // 输出16.28
    }
}

方法2:使用DecimalFormat指定舍入模式

如果需要格式化输出结果,也可以用DecimalFormat并显式设置四舍五入模式:

import java.text.DecimalFormat;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        double x = 16.275;
        DecimalFormat df = new DecimalFormat("#.00");
        // 强制设置四舍五入模式,避免默认行为的不确定性
        df.setRoundingMode(RoundingMode.HALF_UP);
        System.out.println(df.format(x)); // 输出16.28
    }
}

内容的提问来源于stack exchange,提问作者Emm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:27:12