ylangylang
ylangylang

Reputation: 3474

Keeping trailing 0 when converting from str to float

I have the following problem when converting a number with trailing zeros from string to float:

a = 1.100
string_a = str(a)
float_a = float(string_a)
float_a = 1.1

Is there a way to convert str to float while keeping the trailing 0s at the end?

Upvotes: 4

Views: 3240

Answers (1)

Blender
Blender

Reputation: 298046

The zeroes aren't kept in the first place:

>>> 1.100
1.1
>>> 1.100 == 1.1
True

But you can use string formatting to preserve them when you print it out:

>>> 'It works: {:0.3f}'.format(1.1)
'It works: 1.100'
>>> 'And even with integers: {:0.3f}'.format(10000)
'And even with integers: 10000.000'

Upvotes: 10

Related Questions