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

.NET 5中如何实现Decimal除以整数后向下取整保留固定小数位

.NET 5.0 Decimal除法向下取整保留指定小数位的替代实现

以下是几种更安全、更简洁的实现方式,均覆盖你给出的示例场景:


1. 全场景兼容实现(支持正负值,匹配Math.Floor语义)

该实现避免了原写法的int溢出问题,同时严格符合向下取整逻辑,负数也会往更小的数值方向取整:

public static decimal FloorDivide(decimal x, int y, int decimals)
{
    decimal raw = x / y;
    // 构造偏移量,用于抵消Round的四舍五入逻辑
    decimal offset = 5m / (decimal)Math.Pow(10, decimals + 1);
    offset = raw < 0 ? -offset : offset;
    return Math.Round(raw - offset, decimals, MidpointRounding.ToZero);
}

测试结果符合示例要求:

  • FloorDivide(1M, 3, 3) = 0.333M
  • FloorDivide(1M, 7, 3) = 0.142M
  • FloorDivide(1M, 8, 3) = 0.125M

2. 正数场景简化实现(仅适用于x、y均为正数的业务)

如果你的业务场景里被除数、除数都是正数,向下取整等价于直接截断到指定小数位,写法更简洁性能更好:

public static decimal PositiveFloorDivide(decimal x, int y, int decimals)
{
    decimal scale = (decimal)Math.Pow(10, decimals);
    return decimal.Truncate(x / y * scale) / scale;
}

注意:你原本的写法存在溢出风险,当保留小数位d >= 10时,(int)Math.Pow(10, d)会超过int32最大值2147483647,导致强转异常,上述两种实现均规避了该问题。

内容的提问来源于stack exchange,提问作者Romulus Urakagi Ts'ai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:15:02