0

i'd like to convert a decimal to a string, where zeros at the end are preserved. Using str method erases the last zeros.

Example:

number=0.20

Goal: "0.20"

e.g. using: str(number)="0.2" doesn't seem to work.

LSerni
  • 55,617
  • 10
  • 65
  • 107

3 Answers3

1

If you want 2 decimal places use:

number = 0.20
str_number = '%.2f' % number

Number before f indicates the desired number of places.

zipa
  • 27,316
  • 6
  • 40
  • 58
1

This can be done using string formatting.

"{0:.2f}".format(number)

Will return 0.20.

Doing your chosen method won't work because upon declaring number = 0.20 it omits the last zero right away. If you put that into your idle:

number = 0.20
number
0.2

So declaring number as str(number) is doing str(0.2).

August Williams
  • 907
  • 4
  • 20
  • 37
1

Use the % operator with an appropriate format string:

'%1.2f' % number
=> '0.20'
James
  • 65,548
  • 14
  • 155
  • 193