如何获取浮点值的确切字符串格式

时间:2019-04-19 13:38:29

标签: python string-formatting

我有一个浮点值,可以说:

value = 0.12345

我还有其他浮动列表:

values = [1.04, 2.045, 2.0]

我想获取值smth的确切格式,例如:

# result should be'0.5f'
format_str = Formatter.get_float_format(value)

# and apply that format to values in the list
values = [1.04, 2.045, 2.0]
for v in values:
  print({format_str}.format(v))

如何执行此操作? 我仅在问题的第二部分中找到了很多答案,但是找不到找到特定浮点格式的解决方案...

3 个答案:

答案 0 :(得分:2)

def format_floats(reference, values):
    formatted_values = []
    for i in range(len(values)):
        length = len(str(reference)[str(reference).find("."):])-1
        new_float = str(round(values[i], length))
        new_float += "0"*(len(str(reference))-len(new_float))
        formatted_values.append(new_float)

    return formatted_values

if __name__ == '__main__':

    reference = 0.12345
    values = [1.04, 2.045, 2.0]

    print(format_floats(reference, values))

输出:['1.04000','2.04500','2.00000']

答案 1 :(得分:1)

value = 0.12345
values = [1.04, 2.045, 2.0]

value_length = len(str(value).split('.')[-1]) # length of numbers after a coma -> 5
float_format = '{0:.' + str(value_length) + 'f}' # -> {0:.5f}

for v in values:
    print(float_format.format(v))

输出:

1.04000
2.04500
2.00000

答案 2 :(得分:1)

我计算了小数点后的位数,并根据长度创建了格式字符串。

因此2.045的格式字符串将为0.3f0.1f的{​​{1}}等。

2.0

输出看起来像

def get_format(value):

    #dec is the number after decimal point
    dec = str(value).split('.')[1]
    #Created the format string using the number of digits in dec
    format_str = '0.{}f'.format(len(dec))
    print(format_str)
    print(format(value, format_str))

values = [ 0.12345, 1.04, 2.045, 2.0]

for value in values:
    get_format(value)