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

比较两个小数至三位精度时出现错误,请求技术协助

Fixing Your Decimal Comparison Issue

Hey there! I see the problem with your code—let's break it down and fix it.

The core issue here is how floating-point numbers (double) are represented in binary. When you round the value and divide by 1000 again, you're converting back to a double, which can introduce tiny precision errors that make the == comparison fail unexpectedly. For example, even if two values should be equal after rounding to three decimals, their double representations might have minuscule differences that the strict equality check picks up.

Here's the Fix: Compare Scaled Integers Instead

Instead of converting back to a double after rounding, keep the value as an integer. This avoids any floating-point precision issues entirely, since integer comparisons are always exact.

public class DecimalComparator{ 
    public static boolean areEqualByThreeDecimalPlaces(double a, double b){ 
        // Scale both values by 1000 and round to integers
        long scaledA = Math.round(a * 1000);
        long scaledB = Math.round(b * 1000);
        
        // Compare the integers directly
        return scaledA == scaledB;
    } 
}

Why This Works

By multiplying by 1000 and rounding to a long, we're effectively shifting the decimal point three places to the right and turning the value into a whole number. Comparing these integers is precise—no more hidden precision errors from double's binary representation.

Alternative: Use BigDecimal for High Precision

If you need even more control over rounding behavior or are working with very large/small numbers, BigDecimal is a safer choice (it eliminates floating-point inaccuracies entirely):

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

public class DecimalComparator{ 
    public static boolean areEqualByThreeDecimalPlaces(double a, double b){ 
        BigDecimal valueA = new BigDecimal(a).setScale(3, RoundingMode.HALF_UP);
        BigDecimal valueB = new BigDecimal(b).setScale(3, RoundingMode.HALF_UP);
        
        return valueA.equals(valueB);
    } 
}

Just make sure to use equals() instead of == with BigDecimal—== checks object references, not value equality.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:42:32