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?
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
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.
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.
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.
String formatting:
print "%.2f" % 5
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'
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
Shortest Python 3 syntax:
n = 5
print(f'{n:.2f}')
In Python 3
print(f"{number:.2f}")
A shorter way to do format.
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
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.
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.
Using Python 3 syntax:
print('%.2f' % number)
Related
I want to convert a float like a = 1.1234567 to a string, giving the precision as a second variable (which is why this is no duplicate of "Fixed digits after decimal with f-strings"):
def float2str(val, precision):
...
float2str(1.1234567, 3) # '1.123'
float2str(1.1234567, 5) # '1.12346' (mind correct rounding)
I know that f-strings can do the correct rounding using f'{a:.5f}', but the precision has to be part of the string.
I came up with this horribly ugly solutions and hope someone can point me to a more elegant way:
f'%.{precision}f' % a
you have a couple of options, given:
a = 1.1234567
b = 3
we can use either:
using format strings: f'{a:.{b}f}'
using old-style percent formatting: '%.*f' % (b, a)
suppose a float number x=3.1234. I want to print this number in the middle of the string containing space in the left side and right side of x. string length will be variable. Precision of x will be variable. if string length=10 and precision=2 the output will be " 3.14 " Have any function in python that can return this?
This is really nicely documented at https://docs.python.org/3.6/library/string.html#format-specification-mini-language
But since you clearly didn't have time to google for it:
>>> x = 3.1234
>>> length=10
>>> precision=2
>>> f"{x:^{length}.{precision}}"
' 3.1 '
I'm afraid your notion of precision doesn't agree with Python's in the default case. You can fix it by specifying fixed point formatting instead of the default general formatting:
>>> f"{x:^{length}.{precision}f}"
' 3.12 '
This notation is more perspicuous than calling the method str.format(). But in Python 3.5 and earlier you need to do this instead:
>>> "{x:^{length}.{precision}f}".format(x=x, length=length, precision=precision)
But no amount of fiddling with the format is going to make 3.1234 come out as 3.14. I suspect that that was an error in the question, but if you really meant it, then there is no alternative but adjust the value of x before formatting it. Here is one way to do that:
>>> from decimal import *
>>> (Decimal(x) / Decimal ('0.02')).quantize(Decimal('1'), rounding=ROUND_UP) * Decimal('0.02')
Decimal('3.14')
This divides your number into a whole number of chunks of size 0.02, rounding up where necessary, then multiplies by 0.02 again to get the value you want.
For example,
a = 5 * 6.2
print (round(a, 2)
The output is 31.0. I would have expected 31.00.
b = 2.3 * 3.2
print (round(b, 3))
The output is 7.36. I would have expected 7.360.
You are confusing rounding with formatting. Rounding produces a new float object with the rounded value, which is still going to print the same way as any other float:
>>> print(31.00)
31.0
Use the format() function if you need to produce a string with a specific number of decimals:
>>> print(format(31.0, '.2f'))
31.00
See the Format Specification Mini-Language section for what options you have available.
If the value is part of a larger string, you can use the str.format() method to embed values into a string template, using the same formatting specifications:
>>> a = 5 * 6.2
>>> print('The value of "a" is {:.2f}'.format(a))
Python always prints at least one digit after the decimal point so you can tell the difference between integers and floats.
The round() function merely rounds the number to the specified number of decimal places. It does not control how it is printed. 7.36 and 7.360 are the same number, so the shorter is printed.
To control the printing, you can use formatting. For example:
print(".3f" % b)
Python does round to 3 decimal places. It is the printing that cuts additional zeros. Try something like print("%.3f" % number)
I have a list of floats in Python and when I convert it into a string, I get the following
[1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
These floats have 2 digits after the decimal point when I created them (I believe so),
Then I used
str(mylist)
How do I get a string with 2 digits after the decimal point?
======================
Let me be more specific, I want the end result to be a string and I want to keep the separators:
"[1883.95, 1878.33, 1869.43, 1863.40]"
I need to do some string operations afterwards. For example +="!\t!".
Inspired by #senshin the following code works for example, but I think there is a better way
msg = "["
for x in mylist:
msg += '{:.2f}'.format(x)+','
msg = msg[0:len(msg)-1]
msg+="]"
print msg
Use string formatting to get the desired number of decimal places.
>>> nums = [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
>>> ['{:.2f}'.format(x) for x in nums]
['1883.95', '1878.33', '1869.43', '1863.40']
The format string {:.2f} means "print a fixed-point number (f) with two places after the decimal point (.2)". str.format will automatically round the number correctly (assuming you entered the numbers with two decimal places in the first place, in which case the floating-point error won't be enough to mess with the rounding).
If you want to keep full precision, the syntactically simplest/clearest way seems to be
mylist = list(map(str, mylist))
map(lambda n: '%.2f'%n, [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001])
map() invokes the callable passed in the first argument for each element in the list/iterable passed as the second argument.
Get rid of the ' marks:
>>> nums = [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
>>> '[{:s}]'.format(', '.join(['{:.2f}'.format(x) for x in nums]))
'[1883.95, 1878.33, 1869.43, 1863.40]'
['{:.2f}'.format(x) for x in nums] makes a list of strings, as in the accepted answer.
', '.join([list]) returns one string with ', ' inserted between the list elements.
'[{:s}]'.format(joined_string) adds the brackets.
str([round(i, 2) for i in mylist])
Using numpy you may do:
np.array2string(np.asarray(mylist), precision=2, separator=', ')
I am looking to convert some small numbers to a simple, readable output. Here is my method but I wondering if there is something simpler.
x = 8.54768039530728989343156856E-58
y = str(x)
print "{0}.e{1}".format(y.split(".")[0], y.split("e")[1])
8.e-58
This gets you pretty close, do you need 8.e-58 exactly or are you just trying to shorten it into something readable?
>>> x = 8.54768039530728989343156856E-58
>>> print "{0:.1e}".format(x)
8.5e-58
An alternative:
>>> print "{0:.0e}".format(x)
9e-58
Note that on Python 2.7 or 3.1+, you can omit the first zero which indicates the position, so it would be something like "{:.1e}".format(x)
like this?
>>> x = 8.54768039530728989343156856E-58
>>> "{:.1e}".format(x)
'8.5e-58'
Another way of doing it, if you ever want to extract the exponent without doing string manipulations.
def frexp_10(decimal):
logdecimal = math.log10(decimal)
return 10 ** (logdecimal - int(logdecimal)), int(logdecimal)
>>> frexp_10(x)
(0.85476803953073244, -57)
Format as you wish...
There are two answers: one for using the number and one for simple display.
For actual numbers:
>>> round(3.1415,2)
3.14
>>> round(1.2345678e-10, 12)
1.23e-10
The built-in round() function will round a number to an arbitrary number of decimal places. You might use this to truncate insignificant digits from readings.
For display, it matters which version of display you use. In Python 2.x, and deprecated in 3.x, you can use the 'e' formatter.
>>> print "%6.2e" % 1.2345678e-10
1.23e-10
or in 3.x, use:
>>> print("{:12.2e}".format(3.1415))
3.14e+00
>>> print("{:12.2e}".format(1.23456789e-10))
1.23e-10
or, if you like the zeros:
>>> print("{:18.14f}".format(1.23456789e-10))
0.00000000012346