225

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 → 5.00, 5.5 → 5.50, etc). How can I do this in Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
MarathonStudios
  • 3,983
  • 10
  • 40
  • 46

13 Answers13

371

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

"{:.2f}".format(5)
Austin Adams
  • 6,535
  • 3
  • 23
  • 27
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • 26
    Just for completeness, if the decimals is variable, e.g. `d=3`, then the syntax is `"{:.{}f}".format(5, d)` – jurajb May 06 '19 at 11:28
197

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Would it be good idea to convert it into float again like: `float('%.2f' % 5.0)`? – alper Sep 16 '21 at 18:06
  • @alper that would depend entirely on what you need it for...to print text, a string is fine. – toonarmycaptain Aug 16 '22 at 04:16
  • @alper: If the end goal was a `float`, you'd skip the intermediate string and just do `round(myfloat, 2)`; `float('%.2f' % 5.0)` it completely pointless (the string adds a zero, then parsing back to `float` discards it (because `float` has no concept of additional trailing zeroes). – ShadowRanger Sep 22 '22 at 03:07
149

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.

Flimm
  • 136,138
  • 45
  • 251
  • 267
toonarmycaptain
  • 2,093
  • 2
  • 18
  • 29
  • 1
    If the decimals is variable, e.g. `d=3`, then the syntax is `f'My number is {foobar:.{d}f}'` - as commented by @jurajb – starriet May 25 '22 at 02:34
  • You're right. I'd never considered that. It could be `f'My number is {foobar:.{d}{format}}'` too where `format` could be `e`, `f`, `g`, or `n`. – toonarmycaptain May 26 '22 at 04:25
29

String Formatting:

a = 6.789809823
print('%.2f' %a)

OR

print ("{0:.2f}".format(a)) 

Round Function can be used:

print(round(a, 2))

Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.

b = round(a, 2)
print(b)

Use round() - mostly for display purpose.

Debashis Sahoo
  • 5,388
  • 5
  • 36
  • 41
12

String formatting:

print "%.2f" % 5
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • 1
    But all this are strings , so iam not able to do any mathematical operations on them – itsaruns Jan 23 '14 at 06:54
  • @itsaruns Adding empty decimal places makes no difference if you just need to perform mathematical operations on them. You may be looking for `math.floor`, `math.ceil` or `round` – Steen Schütt Apr 17 '14 at 16:37
10

If you actually want to change the number itself instead of only displaying it differently use format()

Format it to 2 decimal places:

format(value, '.2f')

example:

>>> format(5.00000, '.2f')
'5.00'
Josh
  • 2,122
  • 1
  • 21
  • 28
8

Using python string formatting.

>>> "%0.2f" % 3
'3.00'
kevpie
  • 25,206
  • 2
  • 24
  • 28
6

In Python 3

print(f"{number:.2f}")

A shorter way to do format.

oplxy
  • 129
  • 1
  • 1
5

Shortest Python 3 syntax:

n = 5
print(f'{n:.2f}')
Dos
  • 2,250
  • 1
  • 29
  • 39
  • 1
    Already covered by [this answer](https://stackoverflow.com/a/46495453/4518341) from 2 years earlier – wjandrea Jun 14 '20 at 18:02
-1

I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:

Python 3:

>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict) 
0.12_0.13
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 4
    Hi, welcome to Stack Overflow. When answering a question that already has many answers, please be sure to add some additional insight into why the response you're providing is substantive and not simply echoing what's already been vetted by the original poster. This is especially important in "code-only" answers such as the one you've provided. – chb Apr 08 '19 at 18:56
-2

I faced this problem after some accumulations. So What I learnt was to multiply the number u want and in the end divide it to the same number. so it would be something like this: (100(x+y))/100 = x+y if ur numbers are like 0.01, 20.1, 3,05. You can use number * (len(number)-1)**10 if your numbers are in unknown variety.

Herre Z
  • 1
  • 1
  • While giving examples you can format your text to look like actuall code. Check the options in the editor – Smith Jul 31 '22 at 02:15
  • What you're doing with manual fixed point adjustments is better handled by the `decimal` module (which can be set to arbitrary levels of base-10 precision). – ShadowRanger Sep 22 '22 at 03:12
-3

If you want to get a floating point value with two decimal places limited at the time of calling input,

Check this out ~

a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
print(a)                                  # output 3.14 will be printed.
  • Why `eval` a string when you could just `round`? Anyway this doesn't even work properly since if you feed in `5`, you get `5.0` instead of `5.00` like OP wants. – wjandrea Jun 14 '20 at 17:55
-4

Using Python 3 syntax:

print('%.2f' % number)
  • 2
    %-formatting is not new to Python 3, and is already covered by [this answer](https://stackoverflow.com/a/6149026/4518341) from 6 years earlier – wjandrea Jun 14 '20 at 17:57