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

如何用Python实现按给定位数为整数添加小数点的转换功能

整数按指定小数位转浮点数实现方案

你需要的逻辑本质是把整数的小数点向左移动指定位数,对应的数学公式非常简单:待转换整数 ÷ 10的指定小数位次方

用你给出的示例验证完全匹配需求:

  • convert(11098,3) = 11098 ÷ 10^3 = 11098 ÷ 1000 = 11.098
  • convert(11098,2) = 11098 ÷ 10^2 = 11098 ÷ 100 = 110.98

Python代码实现

普通场景(对精度要求不高)

直接用浮点运算即可满足需求:

def convert(num: int, decimal_places: int) -> float:
    if decimal_places < 0:
        raise ValueError("小数位数不能为负")
    return num / (10 ** decimal_places)

高精度场景(如金融计算)

如果需要避免浮点数精度丢失,建议使用decimal模块实现:

from decimal import Decimal

def convert_precise(num: int, decimal_places: int) -> Decimal:
    if decimal_places < 0:
        raise ValueError("小数位数不能为负")
    return Decimal(num) / Decimal(10 ** decimal_places)

测试参考

  • 输入convert(11098, 3) → 输出 11.098
  • 输入convert(11098, 2) → 输出 110.98
  • 输入convert(-4567, 1) → 输出 -456.7
  • 输入convert(89, 0) → 输出 89.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:33:03