2

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)

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

Maybe something like this is more natural?

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

4 Comments

It seems like 14.00006 shall be treated as 14, as it is close enough.
@glglgl: That's not true: float(14.00006) != int(14.00006)
If you want rounding, an answer with round() like F.J's makes the best sense. I was thinking he meant he didn't by "(without 1e-6)".
@sharth Right, but abs(modf(14.0000006)[0]) < 1e-6. So your solution is not the same as the OP's. (Sorry, I forgot two 0s in my previous comment.)
0

You can use this function :

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

1 Comment

x.is_integer() is simpler. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.