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)
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 have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.
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.
So, this may be a simple question but I'm having some trouble finding the answer anywhere.
Take for example I have a simple program where I want to divide a by b like so:
def main():
a = 12345678900000000
b = 1.25
answer = (a / b)
print(answer)
main()
This particular example would result in 9.87654312e+15. How do I get Python to ignore simplifying my number and just give me the whole number?
Thanks in advance, sorry if it's really basic, I wouldn't have asked if I could have found it through Google.
You are seeing the default str() conversion for floating point numbers at work. You can pick a different conversion by formatting the number explicitly.
The format() function can do this for you:
>>> n = 9.87654312e+15
>>> format(n, 'f')
'9876543120000000.000000'
See the Format Specification Mini-Language documentation for more options. The 'f' format is but one of several:
Fixed point. Displays the number as a fixed-point number. The default precision is 6.
The default precision resulting in the .000000 six digits after the decimal point; you can alter this by using .<precision>f instead:
>>> format(n, '.1f')
'9876543120000000.0'
but take into account that decimals are rounded to fit the requested precision.
The g format switches between using exponents (e) and f notation, depending on the size of the number, but won't include decimals if the number is whole; you could use a very large precision with 'g' to avoid printing decimals altogether:
>>> format(n, '.53g')
'9876543120000000'
To be explicit, str(n) is the same as format(n, '.12g'), repr(n) is format(n, '.17g'); both can use the exponent format when the exponent is larger than the precision.
just be more specific about the floating point format
>>> print answer
9.87654312e+15
>>> print "%.20f" % answer
9876543120000000.00000000000000000000
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.