akushyn
akushyn

Reputation: 103

How to get exact string format of float value

I have a float value, let say:

value = 0.12345

And I have a list of other floats :

values = [1.04, 2.045, 2.0]

I would like to get exact format of the value smth like:

# 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))

How to do this? I only found a lot of answers of a second part of my question, but cant find a solution of gettting a specific float format...

Upvotes: 0

Views: 471

Answers (3)

Gokhan Gerdan
Gokhan Gerdan

Reputation: 1480

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))

output: ['1.04000', '2.04500', '2.00000']

Upvotes: 2

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

I counted the number of digits after the decimal point, and created the format string according to the length.

So the format string of 2.045 will be 0.3f, and 0.1f for 2.0 etc.

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)

the output looks like

0.5f
0.12345
0.2f
1.04
0.3f
2.045
0.1f
2.0

Upvotes: 1

Filip Młynarski
Filip Młynarski

Reputation: 3612

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))

Output:

1.04000
2.04500
2.00000

Upvotes: 1

Related Questions