how to print out no more than two decimal digits of accuracy like 5.32 instead of 5.32436675? Is there any keyword regarding this in python.
Try:
a = 5.32436675
print("%.2f" % a)
Remember this is rounding.
If you just want to truncate use this method from this post.
def trunc(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
slen = len('%.*f' % (n, f))
return str(f)[:slen]
print(trunc(a, 2))
You want to round to 2 places, as seen below:
round(number, 2)
Example:
round(5.32436675, 2)
Output:
5.32
This is preferable to float implementations (truncating solutions) because the rounding means the number is still mostly accurate. You don't want 5.319 to get cut off to 5.31 when it should be 5.32!
Happy coding!
According to string format specifications :
>>> "{0:.2f}".format(5.32436675)
5.32
% formatting is getting a bit old. The new way:
print('{:.2f}'.format(5/9))
You can use:
n = 23.232323
print "%.2f" % n
The '.2' here indicates 2 digits after the decimal point.
Related
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)
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)
Using Python 2.7 how do I round my numbers to two decimal places rather than the 10 or so it gives?
print "financial return of outcome 1 =","$"+str(out1)
Use the built-in function round():
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Or built-in function format():
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Or new style string formatting:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Or old style string formatting:
>>> "%.2f" % (1.679)
'1.68'
help on round:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
Since you're talking about financial figures, you DO NOT WANT to use floating-point arithmetic. You're better off using Decimal.
>>> from decimal import Decimal
>>> Decimal("33.505")
Decimal('33.505')
Text output formatting with new-style format() (defaults to half-even rounding):
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.505")))
financial return of outcome 1 = 33.50
>>> print("financial return of outcome 1 = {:.2f}".format(Decimal("33.515")))
financial return of outcome 1 = 33.52
See the differences in rounding due to floating-point imprecision:
>>> round(33.505, 2)
33.51
>>> round(Decimal("33.505"), 2) # This converts back to float (wrong)
33.51
>>> Decimal(33.505) # Don't init Decimal from floating-point
Decimal('33.50500000000000255795384873636066913604736328125')
Proper way to round financial values:
>>> Decimal("33.505").quantize(Decimal("0.01")) # Half-even rounding by default
Decimal('33.50')
It is also common to have other types of rounding in different transactions:
>>> import decimal
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_DOWN)
Decimal('33.50')
>>> Decimal("33.505").quantize(Decimal("0.01"), decimal.ROUND_HALF_UP)
Decimal('33.51')
Remember that if you're simulating return outcome, you possibly will have to round at each interest period, since you can't pay/receive cent fractions, nor receive interest over cent fractions. For simulations it's pretty common to just use floating-point due to inherent uncertainties, but if doing so, always remember that the error is there. As such, even fixed-interest investments might differ a bit in returns because of this.
You can use str.format(), too:
>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23
When working with pennies/integers. You will run into a problem with 115 (as in $1.15) and other numbers.
I had a function that would convert an Integer to a Float.
...
return float(115 * 0.01)
That worked most of the time but sometimes it would return something like 1.1500000000000001.
So I changed my function to return like this...
...
return float(format(115 * 0.01, '.2f'))
and that will return 1.15. Not '1.15' or 1.1500000000000001 (returns a float, not a string)
I'm mostly posting this so I can remember what I did in this scenario since this is the first result in google.
The best, I think, is to use the format() function:
>>> print("financial return of outcome 1 = $ " + format(str(out1), '.2f'))
// Should print: financial return of outcome 1 = $ 752.60
But I have to say: don't use round or format when working with financial values.
When we use the round() function, it will not give correct values.
you can check it using,
round (2.735) and round(2.725)
please use
import math
num = input('Enter a number')
print(math.ceil(num*100)/100)
print "financial return of outcome 1 = $%.2f" % (out1)
A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float.
For example:
>>> out1 = 1.2345
>>> out1 = float(str(out1)[0:4])
>>> out1
May not be super efficient but simple and works :)
Rounding up to the next 0.05, I would do this way:
def roundup(x):
return round(int(math.ceil(x / 0.05)) * 0.05,2)
I am a beginner python programmer and I have learnt the format specifiers in the print statement.so, %3f will mean that the width of the floating point number should be 3.
But,in the following code,output is not like that
import math
print "%3f"%(math.pi)
this code should output 3.1 because we specified the width as 3.
but the output is 3.141593.
My questions:
1.Does specifying only width work for integers and not for floating point numbers?
2.is it must to specify both width and precision while formatting floating point numbers?
Specifying only width works also for floating point numbers. The thing is that the width includes decimal points too. For example, doing:
"%10f" % math.pi # ' 3.141593'
As you can see, the string is 10 characters long. Another thing to take into account here is that by default, python will output 6 decimal points, so doing "%3f" is the same as "%3.6f".
>>> "%3f" % math.pi
'3.141593'
>>> "%3.6f" % math.pi
'3.141593'
>>>
That's why you are not getting your expected output '3.1'. To get that, and knowing the previous concepts you should specify:
"%3.1f" % math.pi
Or just:
"%.1f" % math.pi
I'd just specify the part after the decimal point like this:
>>> print "%.1f"%(math.pi)
3.1
You should also try the arguably better .format method. It offers much more clarity and functionality while formatting. This is will do what you need,
'{:.1f}'.format(math.pi)
You can also specify padding width,if needed, easily like,
'{:6.1f}'.format(math.pi)
You can read up more here https://pyformat.info/
>>> print "%3f" % x
99999.454540
>>> print "%.3f" % x
99999.455
Well the first one in %30.1%f specifies the length of the string/
>>> print "%30.1f" % x
99999.5
Look at this!
>>> print "%.1f" % x
99999.5
See the last one? It has it rounded off. If you don't want to round off then use decimal instead of float.
import math
from decimal import *
getcontext().prec=6
value = Decimal('999.559987').quantize(Decimal('.01'), rounding=ROUND_DOWN)
print str(value)
print '%.2f' % 999.559987
output:
999.55
999.56
%5.3f here is two part. one is integer '5' part and another is floating part '.3'. integer part print the number of space before printing the number. And floating part specify how many number will print after floating point. And there are given so many example previous answer.
This is what I have:
x = 2.00001
This is what I need:
x = 2.00
I am using:
float("%.2f" % x)
But all I get is:
2
How can I limit the decimal places to two AND make sure there are always two decimal places even if they are zero?
Note: I do not want the final output to be a string.
This works:
'%.2f" % float(x)
Previously I answered with this:
How about this?
def fmt2decimals(x):
s = str(int(x*100))
return s[0:-2] + '.' + s[-2:]
AFAIK you can't get trailing zeros with a format specification like %.2f.
If you can use decimal (https://docs.python.org/2/library/decimal.html) instead of float:
from decimal import Decimal
Decimal('7').quantize(Decimal('.01'))
quantize() specifies where to round to.
https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize
Have you taken a look at the decimal module? It allows you to do arithmetic while maintaining the proper precision:
>>> from decimal import Decimal
>>> a = Decimal("2.00")
>>> a * 5
Decimal('10.00')
>>> b = Decimal("0.05")
>>> a * b
Decimal('0.1000')
Python also has a builtin "round" function: x = round(2.00001, 2) I believe is the command you would use.
Well, in Python, you can't really round to two zeroes without the result being a string. Python will usually always round to the first zero because of how floating point integers are stored. You can round to two digits if the second digit is not zero, though.
For example, this:
round(2.00001, 2)
#Output: 2.0
vs this:
round(2.00601, 2)
#Output: 2.01