JuanPablo
JuanPablo

Reputation: 24754

python: float number like integer

I try convert a float to int when the number don't have decimals.

I make this

from math import modf

def float_like_int(n):
    if abs(modf(n)[0]) < 1e-6:
        return int(n)
return n

print float_like_int(10.1)
print float_like_int(10.00001)
print float_like_int(10.000001)
print float_like_int(10.0)

exist a standard function or a more general way ? (without 1e-6)

Upvotes: 2

Views: 771

Answers (4)

vwvolodya
vwvolodya

Reputation: 2344

Those approach that you are using trys to make a number integer if a fractional part is less than 1e-6 (0.000001 ). This means if you have a number 4.000001, (which is float actually) your function will throw away fractional part. You can change 1e-6 to another value and those numbers, which meet your criteria will be converted to int.

Here is my code without any extra modules imported. This code will not throw away any fractional part.

def Func(a):
    if (a * 10) % 10 == 0:
        return int(a)
    else:
        return a
f = 4.03
print Func(23.45)
print Func(f)
print Func(2.3)

Upvotes: 3

mrlouhibi
mrlouhibi

Reputation: 121

You can use this function :

def isWhole(x):
    if(x%1 == 0):
        return True
    else:
        return False

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208435

I think the following is a bit more readable than your version:

def float_like_int(n):
    if round(n, 6) == round(n):
        return int(round(n))
    return n

Note that this does have a slightly different meaning than your function, since it would also round something like 9.9999999 to 10.

Upvotes: 3

Murph
Murph

Reputation: 1509

Maybe something like this is more natural?

def float_like_int(n):
    if int(n) == float(n):
        return int(n)
    else:
        return float(n)

Upvotes: 1

Related Questions