3

I have the following:

'{0:n}'.format(0/10.0)

which evaluates to

0

I want it to evaluate to

0.0

That is, there should always be 1 decimal place. What is the correct format for this?

Thanks.

Doo Dah
  • 3,979
  • 13
  • 55
  • 74

3 Answers3

9
print('{0:3.1f}'.format(0/10.0))  # '0.0'

f for fixed-point notation; 3 for the total number of places to be reserved for the whole string, 1 for the decimal places.

if your number is too big to fit into the 3 reserved spaces, the string will use more space:

print('{0:3.1f}'.format(10.0))  # '10.0'; 4 places

with a more recent python version you can use f-strings (i put the value in a variable for more legibility)

x= 0/10.0
print('f{x:3.1f}')
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Problem with this is, the docs say that n "uses the current locale setting to insert the appropriate number separator characters." My format string needs to be localized properly. – Doo Dah Aug 09 '17 at 14:20
  • 1
    `f` is actually a float presentation type which stands for 'fixed-point notation'. [See the docs](https://docs.python.org/3/library/string.html#format-specification-mini-language). – daviewales Jul 26 '21 at 03:15
  • 1
    @daviewales ah, yes, that is correct. will update the answer. thanks! – hiro protagonist Jul 26 '21 at 12:00
6
In [24]: "{0:.1f}".format(0)
Out[24]: '0.0'
Cory Madden
  • 5,026
  • 24
  • 37
0

If you change the data to float you the decimal . a= 1.0 # "a" is a float a= 1 # "a" is now a integer

try that :)