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

求助:实现灵活的按指定20倍数取整并支持偏移的方法

解决方案:灵活取整至指定量级的20倍数并偏移

核心逻辑梳理

先明确20的量级计算规则:

  • 当小数位数numOfDecimalPlaces ≤1时,量级为20(即20×10⁰)
  • 当小数位数>1时,量级为20 × 10^-(numOfDecimalPlaces - 1),比如5位小数时,量级是20×10^-4=0.0020

处理步骤:

  1. 计算对应量级的步长step
  2. 将目标价格取整到最近的step倍数
  3. 根据偏移个数(正数向上、负数向下)调整结果
  4. 用decimal类型避免浮点精度损失(推荐用于价格场景)

修正后的C#实现

public static decimal GetAdjusted20Multiple(int numOfDecimalPlaces, int offsetCount, decimal price)
{
    // 计算步长step:20的对应量级
    int exponent = numOfDecimalPlaces <= 1 ? 0 : -(numOfDecimalPlaces - 1);
    decimal step = 20m * (decimal)Math.Pow(10, exponent);
    
    // 取整到最近的step倍数
    decimal nearestMultiple = Math.Round(price / step) * step;
    
    // 应用偏移
    decimal result = nearestMultiple + offsetCount * step;
    
    // 格式化到对应小数位数,避免末尾多余的0(可选,按需调整)
    int decimalPlaces = numOfDecimalPlaces <= 1 ? 0 : numOfDecimalPlaces - 1;
    return Math.Round(result, decimalPlaces);
}

测试示例验证

  1. 示例1:数字1.09426(5位小数),向上偏移2个倍数

    • 步长计算:20×10^-(5-1)=0.0020
    • 最近倍数:Math.Round(1.09426m / 0.0020m)=547 → 547×0.0020=1.0940
    • 偏移后结果:1.0940 + 2×0.0020=1.0980,与需求一致
  2. 示例2:数字1234.5(1位小数),向上偏移2个倍数

    • 步长=20
    • 最近倍数:Math.Round(1234.5m /20)=62 → 62×20=1240
    • 偏移后结果:1240 +2×20=1280,符合需求中“有效20倍数为1300、1280等”的描述

关键改进点

  • 移除了冗余的fractionAsDecimal参数,直接通过小数位数计算步长,逻辑更清晰
  • 使用decimal类型处理价格,避免double的浮点精度误差(比如0.0020用double存储可能出现近似值)
  • 明确偏移规则:正数向上、负数向下,完全匹配需求中的“向上或向下偏移”要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:29:58