Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: return float 1.0 as int 1 but float 1.5 as float 1.5 [duplicate]

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.

like image 478
Raymond Shen Avatar asked Apr 04 '19 07:04

Raymond Shen


People also ask

Can you multiply float and int in Python?

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.

Is 1.0 A float Python?

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.

How do I print 1.0 instead of 1 in Python?

") elif b > 0: print("Y = "+ str(m) +"X + "+ str(b) +". ") elif b == 0: print("Y = "+ str(m) +"X. ") input("Press enter to continue. ")

What is the result of float 1 in Python?

In modern python3 (IIRC since python 3.2) a float that prints as 1.0 is exactly 1.0.


2 Answers

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] 
like image 155
DirtyBit Avatar answered Sep 24 '22 23:09

DirtyBit


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' 
like image 26
Eric Duminil Avatar answered Sep 22 '22 23:09

Eric Duminil