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

如何修复jdeprscan检测到的BigDecimal.divide过时方法警告?

Fixing the Deprecated BigDecimal.divide(BigDecimal, int) Warning in Your Java Code

Let's break down how to resolve this deprecation warning you're seeing from jdeprscan.

First, the root cause: Java 9 marked the BigDecimal.divide(BigDecimal, int) method as deprecated because it relies on integer constants (like BigDecimal.ROUND_HALF_UP) for rounding modes. The recommended replacement is the overload that uses the RoundingMode enum, which is more type-safe and readable.

Looking at your current code:

/** 
 * Convert duration milliseconds to seconds suitable for displaying.
 * 
 * 246 milliseconds -> '0.246 secs' 
 */ 
public String getDurationForDisplay() { 
    BigDecimal duration = new BigDecimal("" + requestDuration).setScale(3); 
    duration = duration.divide(new BigDecimal("1000"), BigDecimal.ROUND_HALF_UP); 
    return "" + duration + " secs"; 
}

Step-by-Step Fix

  • Replace the deprecated method call: Swap the integer rounding constant with the corresponding RoundingMode enum value.
  • Import the enum if missing: Add import java.math.RoundingMode; to the top of your class if it's not already present.

Here's the updated code:

import java.math.RoundingMode;

// ...

/** 
 * Convert duration milliseconds to seconds suitable for displaying.
 * 
 * 246 milliseconds -> '0.246 secs' 
 */ 
public String getDurationForDisplay() { 
    BigDecimal duration = new BigDecimal(String.valueOf(requestDuration)).setScale(3); 
    // Use RoundingMode.HALF_UP instead of BigDecimal.ROUND_HALF_UP
    duration = duration.divide(new BigDecimal("1000"), RoundingMode.HALF_UP); 
    return duration + " secs"; 
}

Bonus Optimizations (Cleaner, More Efficient Code)

  • If requestDuration is a numeric type (like long or int), skip string conversion entirely: new BigDecimal(requestDuration) is more efficient than converting to a string first.
  • Extract the 1000 value into a static constant to avoid recreating the BigDecimal object on every method call:
private static final BigDecimal MILLISECONDS_TO_SECONDS = new BigDecimal("1000");

public String getDurationForDisplay() { 
    BigDecimal duration = new BigDecimal(requestDuration).setScale(3); 
    duration = duration.divide(MILLISECONDS_TO_SECONDS, RoundingMode.HALF_UP); 
    return duration + " secs"; 
}

After making these changes, re-run your jdeprscan command, and the deprecation warning should no longer appear.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:49:14