In Python is there a way to turn 1.0
into a integer 1
while the same function ignores 1.5
and leaves it as a float
?
Right now, int()
will turn 1.0
into 1
but it will also round 1.5
down to 1
, which is not what I want.
Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float . The multiplication result will always be of type float . Copied! The first example uses the input() function to get an integer from the user.
In Python, if you declare a number without a decimal point it is automatically considered an integer. The values that have a decimal point (e.g., 6.00, 2.543, 233.5, 1.0) are referred to as float.
") elif b > 0: print("Y = "+ str(m) +"X + "+ str(b) +". ") elif b == 0: print("Y = "+ str(m) +"X. ") input("Press enter to continue. ")
In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0.
Continuing from the comments above:
Using is_integer()
:
Example from the docs:
>>> (1.5).is_integer() False >>> (1.0).is_integer() True >>> (1.4142135623730951).is_integer() False >>> (-2.0).is_integer() True >>> (3.2).is_integer() False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s): return [int(x) if x.is_integer() else x for x in s] print(func(s))
If you do not want any import
:
def func(s): return [int(x) if x == int(x) else x for x in s] print(func(s))
Using map()
with lambda
function and the iter s
:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT:
[1.5, 1, 2.5, 3.54, 1, 4.4, 2]
In case your goal is to convert numbers to a concise string, you could simply use '%g'
("General Format") for formatting:
>>> '%g' % 1.0 '1' >>> '%g' % 1 '1' >>> '%g' % 1.5 '1.5' >>> '%g' % 0.3 '0.3' >>> '%g' % 0.9999999999 '1'
You can specify the desired accuracy:
>>> '%.15g' % 0.999999999999999 '0.999999999999999' >>> '%.2g' % 0.999 '1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With