Mapping a two decimal place float in Python

I have a function that takes float arguments (usually integers or decimal numbers 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?

+85
python string floating-point programming-languages
May 27 '11 at 7:13 a.m.
source share
8 answers

To do this, you can use the string formatting operator:

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

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

+119
May 27 '11 at 7:15
source share

Since this post may be here for a while, let's also point out the Python 3 syntax:

 "{:.2f}".format(5) 
+192
May 27 '11 at 7:22
source share

f-string formatting:

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

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

You can see in this example that we format with decimal places similarly to the previous string formatting methods.

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

Further, with the new code, f-lines should be preferable to the usual methods% s or str.format (), since f-lines are much faster .

+27
Sep 29 '17 at 19:06 on
source share

String formatting:

 print "%.2f" % 5 
+6
May 27 '11 at 7:14
source share

Using python string formatting.

 >>> "%0.2f" % 3 '3.00' 
+4
May 27 '11 at 7:16
source share

Using Python 3 syntax:

 print('%.2f' % number) 
+1
Aug 10 '17 at 23:55 on
source share

If you really want to change the number itself, and not just display it differently, use format ()

Format it to 2 decimal places:

 format(value, '.2f') example: >>> format(5.00000, '.2f') '5.00' 
+1
Jan 24 '19 at 7:53
source share

I know this is an old question, but I struggled to find the answer myself. Here is what I came up with:

Python 3:

 num_dict = { 'num': 0.123, 'num2':0.127} "{0[num]:.2f}_{0[num]:.2f}".format(num_dict) #output: 0.12_0.13 
0
Apr 08 '19 at 18:39
source share



All Articles