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
  • 53,899
  • 9
  • 63
  • 106

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
  • 26,044
  • 6
  • 38
  • 55
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
  • 837
  • 1
  • 17
  • 34
1

Use the % operator with an appropriate format string:

'%1.2f' % number
=> '0.20'
James
  • 63,608
  • 14
  • 148
  • 190