How to display a float with two decimal places? [duplicate]
Asked Answered
H

13

244

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?

Harriettharrietta answered 27/5, 2011 at 7:13 Comment(0)
Z
202

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.

Zebec answered 27/5, 2011 at 7:15 Comment(3)
Would it be good idea to convert it into float again like: float('%.2f' % 5.0)?Defeatist
@Defeatist that would depend entirely on what you need it for...to print text, a string is fine.Eck
@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).Phail
Q
390

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

"{:.2f}".format(5)
Quadruplex answered 27/5, 2011 at 7:22 Comment(1)
Just for completeness, if the decimals is variable, e.g. d=3, then the syntax is "{:.{}f}".format(5, d)Suggestive
Z
202

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.

Zebec answered 27/5, 2011 at 7:15 Comment(3)
Would it be good idea to convert it into float again like: float('%.2f' % 5.0)?Defeatist
@Defeatist that would depend entirely on what you need it for...to print text, a string is fine.Eck
@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).Phail
E
159

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.

Eck answered 29/9, 2017 at 19:6 Comment(2)
If the decimals is variable, e.g. d=3, then the syntax is f'My number is {foobar:.{d}f}' - as commented by @SuggestivePetticoat
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.Eck
D
28

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.

Dissimilar answered 21/11, 2019 at 10:11 Comment(3)
Downvote for round. It should not be used just for display purposes.Whoops
@Whoops I respect your comment, but this answers are just to satisfy someone's requirement.Dissimilar
@debaonline4u wim is right. round(5.0001, 2) -> 5.0, not '5.00'Gyp
H
12

String formatting:

print "%.2f" % 5
Hautegaronne answered 27/5, 2011 at 7:14 Comment(2)
But all this are strings , so iam not able to do any mathematical operations on themYork
@York 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 roundNomanomad
I
11

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'
Ingeringersoll answered 24/1, 2019 at 7:53 Comment(0)
G
8

Using python string formatting.

>>> "%0.2f" % 3
'3.00'
Gagger answered 27/5, 2011 at 7:16 Comment(0)
E
8

In Python 3

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

A shorter way to do format.

Expectorate answered 14/5, 2021 at 15:23 Comment(1)
Already covered by this answer from four years earlier.Phail
W
5

Shortest Python 3 syntax:

n = 5
print(f'{n:.2f}')
Want answered 3/12, 2019 at 12:44 Comment(1)
Already covered by this answer from 2 years earlierGyp
E
-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
Evzone answered 8/4, 2019 at 18:39 Comment(1)
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.Frankhouse
T
-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.

Trickery answered 28/7, 2022 at 20:22 Comment(2)
While giving examples you can format your text to look like actuall code. Check the options in the editorAristocracy
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).Phail
P
-4

Using Python 3 syntax:

print('%.2f' % number)
Peach answered 10/8, 2017 at 23:55 Comment(1)
%-formatting is not new to Python 3, and is already covered by this answer from 6 years earlierGyp
R
-4

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.
Right answered 15/4, 2020 at 6:55 Comment(1)
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.Gyp

© 2022 - 2024 — McMap. All rights reserved.