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.
If you want 2 decimal places use:
number = 0.20
str_number = '%.2f' % number
Number before f
indicates the desired number of places.
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)
.
Use the %
operator with an appropriate format string:
'%1.2f' % number
=> '0.20'