Ok, please bear with me, I'm completely new to this. This is for school, and the exact syntax isn't important here for my assignment, but for my own personal knowledge I want to know a little more about string formatting.
whenever I use %f it defaults to 2 decimal places. Is there a string format that I can use on a float that will show the float with the number of decimals it actually has?
for instance my list contains 2.0, 2.01, 2.001, 2.0001 and I want to use a string format to print them as they look. Which format code would I use or how could I use %f properly if possible?
This is in Python 2.7 on Windows 7(if that matters).
%g may be what you're looking for:
>>> "%g, %g, %g, %g" % (2.1, 2.01, 2.001, 2.0001)
'2.1, 2.01, 2.001, 2.0001'
If you convert the float to a string, then when you print it, it will be displayed just as you wrote it.
>>> x = str(2.0)
>>> print(x)
2.0
>>> x = str(2.01)
>>> print(x)
2.01
>>> x = str(2.001)
>>> print(x)
2.001
>>> x = str(2.0001)
>>> print(x)
2.0001
(In fact, to be precise, in Python you're not actually converting the floating point object, but creating a string object that looks like it. But that's a bit outside of the scope of your question.)
UPDATE
Someone posted a way to remove trailing zeros from floating point numbers using the Decimal class, here: Removing Trailing Zeros in Python
Related
I am new to python.
In python, I wish to convert float variables to string variable with 2 decimal places and decimal comma.
For example, 3.1415 --> 3,14
it works fine. But when I convert 1.20, it gives 1,2 instead of 1,20.
I want the latter one
Is there an easy way to achieve that? Thank You Guys
My code is in the following:
s=float(input())
a=round(s,2)
x=str(a)
y=x.replace('.',','))
print(y)
Try using this:
>>> num = 1.201020
>>> '{:.2f}'.format(num).replace('.', ',')
'1,20'
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
You could use:
s = '23.245678'
i = int(float(s))
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
I believe this is a useless bug that should be corrected in Python.
int('2') --> 2 That converts the string '2' into an the integer 2.
int(2.7) --> 2 Converts a float to an int.
int('2.7') SHOULD convert to 2. This is how Perl works, for example. Yes, this does two things at once. It converts the string and when it finds it is in a representation that is a float, it should convert to int.
Otherwise, why insist that float('2') should work? It is an integer string, because there is no decimal point. So it has to convert from string which is an integer, directly to float.
I don't know but perhaps someone can answer whether the python interpreter, if the required int(float(x)) is used, if it actually goes through the process of first converting to float and then converting to int. That would make this bug even more critical to correct.
I am reading in data from a file, modify it and write it to another file. The new file will be read by another program and therefore it is crucial to carry over the exact formatting
for example, one of the numbers on my input file is:
1.000000
my script applies some math to the columns and should return
2.000000
But what is currently returned is
2.0
How would I write a float for example my_float = 2.0, as my_float = 2.00000 to a file?
Format it to 6 decimal places:
format(value, '.6f')
Demo:
>>> format(2.0, '.6f')
'2.000000'
The format() function turns values to strings following the formatting instructions given.
From Python 3.6 it's also possible to do f-string formatting. This looks like:
f"{value:.6f}"
Example:
> print(f"{2.0:.6f}")
'2.000000'
I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.
foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))
output:
56.0
56.00
56.000
56.00000
Meaning that the 2nd argument of format takes the decimal places you'd have to go up to. Keep in mind that format returns string.
I've had problems with using variables in f strings. When all else fails, read the manual :)
"A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal."
https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Case in point:
my_number = 90000
zeros = '.2f'
my_string = f"{my_number:,{zeros}}"
print (my_string)
90,000.00
my_string = f'{my_number:,{zeros}}'
will not work, because of the single quotes.
Quotes containing the f string and the string
variable used in the f string should be
different.
If using single quotes for the string variable,
use double quotes for the f module and vice versa.
An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:
>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python limiting floats to two decimal points
i want to set 39.54484700000000 to 39.54 using python ,
how to get it ,
thanks
If you want to change the actual value, use round as Eli suggested. However for many values and certain versions of Python this will not result be represented as the string "39.54". If you want to just round it to produce a string to display to the user, you can do
>>> print "%.2f" % (39.54484700000000)
39.54
or in newer versions of Python
>>> print("{:.2f}".format(39.54484700000000))
39.54
or with the fstrings
>>> print(f'{39.54484700000000:.2f}')
39.54
Relevant Documentation: String Formatting Operations, Built-in Functions: round
How about round
>>> import decimal
>>> d=decimal.Decimal("39.54484700000000")
>>> round(d,2)
39.54
You can use the quantize method if you're using a Decimal:
In [24]: q = Decimal('0.00')
In [25]: d = Decimal("115.79341800000000")
In [26]: d.quantize(q)
Out[26]: Decimal("115.79")
>>> round(39.54484700000000, 2)
39.54
Note, however, that the result isn't actually 39.54, but 39.53999999999999914734871708787977695465087890625.
Use round:
Return the floating point value x
rounded to n digits after the decimal
point. If n is omitted, it defaults to
zero. The result is a floating point
number.
Values are rounded to the closest
multiple of 10 to the power minus n;
if two multiples are equally close,
rounding is done away from 0
>>> round(39.544847, 2)
39.539999999999999
>>>
Note that since 39.54 isn't exactly represantable with floating points on my PC (x86), the result is an epsilon off. But that makes no difference (and is a whole different issue with many SO questions and answers on it). If you convert it to a string properly, you'll see what you expect:
>>> "%.2f" % round(39.544847, 2)
'39.54'
Eli mentions using the round function -- depending on your requirements, you may want to return a Decimal object instead.
>>> from decimal import Decimal
>>> float_val = 39.54484700000000
>>> decimal_val = Decimal("%.2f" % float_val)
>>> print decimal_val
39.54
Using Decimal objects lets you specify the exact number of decimal places that you want to keep track of, so you avoid ending up with a floating point number that is represented as 39.539999999999999. Specifically, if you are doing financial calculations, you will almost always be advised to stay away from floating-point numbers.
You can't cast floats directly into Decimals, however (the floats are imprecise, and Python can't guess how you want them rounded,) so I will almost always convert them to a rounded string representation first (that's the "%.2f" % float_val -- %.2f means to display only two decimals, and then create a Decimal out of that.
How do I round a decimal to a particular number of decimal places using the Python 3.0 format function?
Here's a typical, useful example...:
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
the nested {1} takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting {0:.4f} then applies. Of course, you can hardcode the 4 (or whatever number of digits) if you wish, but the key point is, you don't have to!
Even better...:
>>> '{number:.{digits}f}'.format(number=p, digits=n)
'3.1416'
...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format -- that can be so much more readable, as you see!!!
An updated answer based on [Alex Martelli]'s solution but using Python 3.6.2 and it's updated format syntax I would suggest:
>>> n=4
>>> p=math.pi
>>> f'{p:.{n}f}'
'3.1416'
But by choosing your variables wisely your code becomes self documenting
>>> precision = 4
>>> pi = math.pi
>>> f'{pi:.{precision}f}'
'3.1416'
In Python 3.x a format string contains replacement fields indicated by braces thus::
".... {0: format_spec} ....".format(value)
The format spec has the general layout:
[[fill]align][sign][pad][width][,][.precision][type]
So, for example leaving out all else but width, precision and type code, a decimal or floating point number could be formatted as:
>>>print("The value of pi is {0:10.7f} to 7 decimal places.".format(math.pi))
This would print as:
The value of pi is 3.1415927 to 7 decimal places.
To round x to n decimal places use:
"{0:.{1}f}".format(x,n)
where 0 and 1 stand for the first and second arguments of the str.format() method, respectively.
I just found out that it is possible to combine both the {0} and the {digits} notation. This is especially useful when you want to round all variables to a pre-specified number of decimals with 1 declaration:
sName = 'Nander'
fFirstFloat = 1.12345
fSecondFloat = 2.34567
fThirdFloat = 34.5678
dNumDecimals = 2
print( '{0} found the following floats: {1:.{digits}f}, {2:.{digits}f}, {3:.{digits}f}'.format(sName, fFirstFloat, fSecondFloat, fThirdFloat, digits=dNumDecimals))
# Nander found the following floats: 1.12, 2.35, 34.57
=============================================================
EDIT:
Since all answers (including mine) where using the 'old' {0}.format() method, I'm now adding the new f-strings method (Formatted String Literals, Python 3.6+ I think) too:
x = 1.2345
y = 23.45678
print(f'x = {x:.2f} and y = {y:.2f}')
#x = 1.23 and y = 23.46