Safest way to convert float to integer in python?
All integers that can be represented by floating point numbers have an exact representation. So you can safely use int
on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.
That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.
To quote from Wikipedia,
Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.
How do I parse a string to a float or int?
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Python float to Decimal conversion
Python <2.7
"%.15g" % f
Or in Python 3.0:
format(f, ".15g")
Python 2.7+, 3.2+
Just pass the float to Decimal
constructor directly, like this:
from decimal import Decimal
Decimal(f)
Value error converting from float to int in python (very weird problem)
https://docs.python.org/3/library/functions.html#int
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
It is rejecting the decimal point in your input string when you pass it to the builtin int
function.
num = "1.5"
print(type(num)) # <class 'str'>
print(int(num)) # ValueError: invalid literal for int() with base 10: '1.5'
num = "2"
print(type(num)) # <class 'str'>
print(int(num)) #2
num = 1.5
print(type(num)) # <class 'float'>
int_num = int(num)
print(type(int_num)) # <class 'int'>
print(int_num) # 1
num = "1.5"
float_num = float(num)
print(type(float_num)) # <class 'float'>
print(float_num) # 1.5
int_num = int(float_num)
print(type(int_num)) # <class 'int'>
print(int_num) # 1
Convert floats to ints in Pandas?
To modify the float output do this:
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
a
0 0
1 1
2 2
3 3
4 4
How to convert int to float in python?
Other than John's answer, you could also make one of the variable float, and the result will yield float.
>>> 144 / 314.0
0.4585987261146497
Python: Convert Float to Int in List
Please try to provide full error traceback documentation in future posts to help people better assist you.
It's fundamentally impossible to concatenate type int
to a str
initialization unless you cast the int
as a str
(i.e., the opposite of what you're trying to do). I'm not really sure what your end goal is here, but I can assure you that the problem is not that the strings which you are trying to cast as integers are not being converted (in the case where they are numbers in string form), it's rather just that you can't concatenate them to an empty string.
If there's something else you're trying to do here, I can try to help if you can elaborate.
Convert float to integer to get number without dot and zero
If you are dealing with numpy
array you can do the following
y = np.array(np.round(x), dtype=int)
However if its just a number int(round(x))
will do the job.
Related Topics
Python Replace String Pattern with Output of Function
Recursively Iterate Through All Subdirectories Using Pathlib
How to Get the Domain Name of My Site Within a Django Template
Can Pandas Plot a Histogram of Dates
Return SQL Table as JSON in Python
Python Subprocess and User Interaction
Positional Argument Follows Keyword Argument
Double Precision Floating Values in Python
Django Rest Framework Post Nested Objects
Best Way to Parse a Url Query String
Python Argparse Conditionally Required Arguments
Call Class Method from Another Class
Why am I Getting a Nameerror When I Try to Call My Function
Argparse with Required Subparser