使用最小和最大小数位数格式化float

时间:2015-09-06 19:54:40

标签: python-3.x string-formatting

我想格式化一个最小2位和最多8位小数的浮点数。我是这样做的:

def format_btc(btc):
    s = locale.format("%.8f", btc).rstrip('0')
    if s.endswith(','):
        s += '00'
    return s

有没有办法只使用format()函数?

编辑:

示例:左边是浮点数,右边是字符串

1 -> 1,00
1.1 -> 1,10 (I have now realised that my code returns 1,1 for this example; that's a bug)
1.12 -> 1,12
1.123 -> 1,123
1.12345678 -> 1,12345678
1.123456789 -> 1,12345678
1,1234567890 -> 1,12345678

1 个答案:

答案 0 :(得分:1)

没有。我重新检查specification language以确保。可能的原因:

  1. (理论)如果十进制后8位有效,则删除0将删除信息。

  2. (实用)添加第三个数字参数的复杂性仅用于浮点数然后很少是不可行的。

相关问题