如何用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
相关产品推荐
相关产品推荐

