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

带小数价格按阈值4就近舍入末位为9的简洁实现方法

价格调整通用解决方案

直接通过数学运算实现,无需转字符串处理,天然适配1~N位整数的价格场景,逻辑简洁效率更高。

核心逻辑

  1. 拆分价格的整数部分和小数部分
  2. 取整数部分的末位数字做判定:
    • 若小数部分>0且末位≥4,或末位>4,向上调整到最近的末位为9的整数
    • 其余情况向下调整到最近的末位为9的整数

实现代码

def adjust_price(price):
    # 拆分整数、小数部分
    int_part = int(price)
    decimal_part = price - int_part
    last_digit = int_part % 10
    
    # 阈值判定
    if (decimal_part > 1e-6 and last_digit >= 4) or last_digit > 4:
        # 向上取最近的9结尾整数
        return int_part + (9 - last_digit)
    else:
        # 向下取最近的9结尾整数,适配个位数场景避免返回负数
        res = int_part - (last_digit + 1)
        return res if res >= 9 else 9

注:decimal_part > 1e-6是为了规避浮点数精度误差问题,如果你的价格是字符串传入转的Decimal类型,直接判断decimal_part > 0即可。

验证测试

所有示例均符合预期:

  • adjust_price(734) → 729
  • adjust_price(734.1) → 739
  • adjust_price(733.9) → 729
  • adjust_price(757.2) → 759
  • adjust_price(24) → 19
  • adjust_price(24.5) → 29
  • adjust_price(1234.01) → 1239

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:54:02