【问题标题】:Length of a float without trailing zeros (python)没有尾随零的浮点数的长度(python)
【发布时间】:2022-01-18 12:44:23
【问题描述】:

我想使用 python 打印一个浮点数的长度而不用尾随零。 例子:

0.001000 >>> I want to get length=5

0.000100 >>> I want to get length=6

0.010000 >>> I want to get length=4

有什么建议吗?

【问题讨论】:

    标签: python precision zero trailing


    【解决方案1】:

    将 float 转换为 str 将自动删除拖尾零:

    numbers = [0.0010000, 0.00000000100, 0.010000]
    
    for number in numbers:
        number = '{0:.16f}'.format(number).rstrip("0")
        print(f"Converted to String: {str(number)} - Length: {len(str(number))}")
    

    结果:

    Converted to String: 0.001 - Length: 5
    Converted to String: 0.000000001 - Length: 11
    Converted to String: 0.01 - Length: 4
    

    【讨论】:

    • 对于超过 4 个零的数字,它显示 '1e-05' 示例:(str(float(0.00001))) >>> '1e-05' (str(float(0.000001)) ) >>> '1e-06' 然后它会计算错误的长度
    • @OmarAl-khader 更新了答案。
    【解决方案2】:

    试试这个:

    inp = '0.00100'
    len(str(float(inp)))
    

    输出:

    长度为 5

    所有尾随零都将被删除。

    【讨论】:

    • 对于超过 4 个零的数字,它显示 '1e-05' 示例:(str(float(0.00001))) >>> '1e-05' (str(float(0.000001)) ) >>> '1e-06' 然后它会计算错误的长度
    猜你喜欢
    • 2011-01-27
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2018-11-15
    相关资源
    最近更新 更多