The Python Oracle

How to display a float with two decimal places?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands

--

Chapters
00:00 How To Display A Float With Two Decimal Places?
00:22 Answer 1 Score 12
00:31 Accepted Answer Score 203
00:47 Answer 3 Score 393
00:58 Answer 4 Score 162
01:55 Thank you

--

Full question
https://stackoverflow.com/questions/6149...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #floatingpoint

#avk47



ANSWER 1

Score 393


Since this post might be here for a while, lets also point out python 3 syntax:

"{:.2f}".format(5)



ACCEPTED ANSWER

Score 203


You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.




ANSWER 3

Score 162


f-string formatting:

This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.

>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

You can see in this example we format with decimal places in similar fashion to previous string formatting methods.

NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.




ANSWER 4

Score 12


String formatting:

print "%.2f" % 5