IT

숫자가 int인지 float인지 확인하십시오.

lottoking 2020. 5. 27. 07:59
반응형

숫자가 int인지 float인지 확인하십시오.


내가 한 방법은 다음과 같습니다.

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

그런 것.
더 좋은 방법이 있습니까?


isinstance를 사용하십시오 .

>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True

그래서:

>>> if isinstance(x, int):
        print 'x is a int!'

x is a int!

_편집하다:_

지적한 바와 같이, 긴 정수의 경우 위의 작동하지 않습니다. 따라서 다음을 수행해야합니다.

>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False

@ninjagecko의 답변이 가장 좋습니다.

이것은 또한 작동합니다 :

Python 2.x 용

isinstance(n, (int, long, float)) 

파이썬 3.x는 오래 가지 않습니다

isinstance(n, (int, float))

복소수에 대한 복소수 유형도 있습니다


짧막 한 농담:

isinstance(yourNumber, numbers.Real)

이것은 몇 가지 문제를 피합니다.

>>> isinstance(99**10,int)
False

데모:

>>> import numbers

>>> someInt = 10
>>> someLongInt = 100000L
>>> someFloat = 0.5

>>> isinstance(someInt, numbers.Real)
True
>>> isinstance(someLongInt, numbers.Real)
True
>>> isinstance(someFloat, numbers.Real)
True

허락을 구하는 것보다 용서를 구하는 것이 더 쉽습니다. 간단히 작업을 수행하십시오. 그것이 작동한다면, 물체는 수용 가능하고 적합하며 적절한 유형이었습니다. 작업이 작동하지 않으면 개체 유형이 적절하지 않은 것입니다. 유형을 아는 것은 거의 도움이되지 않습니다.

작업을 시도하고 작동하는지 확인하십시오.

inNumber = somenumber
try:
    inNumberint = int(inNumber)
    print "this number is an int"
except ValueError:
    pass
try:
    inNumberfloat = float(inNumber)
    print "this number is a float"
except ValueError:
    pass

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

Here's a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.

import sys

if sys.version < '3':
    integer_types = (int, long,)
else:
    integer_types = (int,)

isinstance(yourNumber, integer_types)  # returns True if it's an integer
isinstance(yourNumber, float)  # returns True if it's a float

Notice that Python 2 has both types int and long, while Python 3 has only type int. Source.

If you want to check whether your number is a float that represents an int, do this

(isinstance(yourNumber, float) and (yourNumber).is_integer())  # True for 3.0

If you don't need to distinguish between int and float, and are ok with either, then ninjagecko's answer is the way to go

import numbers

isinstance(yourNumber, numbers.Real)

You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"

I know it's an old thread but this is something that I'm using and I thought it might help.

It works in python 2.7 and python 3< .

def is_float(num):
    """
    Checks whether a number is float or integer

    Args:
        num(float or int): The number to check

    Returns:
        True if the number is float
    """
    return not (float(num)).is_integer()


class TestIsFloat(unittest.TestCase):
    def test_float(self):
        self.assertTrue(is_float(2.2))

    def test_int(self):
        self.assertFalse(is_float(2))

pls check this: import numbers

import math

a = 1.1 - 0.1
print a 

print isinstance(a, numbers.Integral)
print math.floor( a )
if (math.floor( a ) == a):
    print "It is an integer number"
else:
    print False

Although X is float but the value is integer, so if you want to check the value is integer you cannot use isinstance and you need to compare values not types.


how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever

Tried in Python version 3.6.3 Shell

>>> x = 12
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x,int)
True

Couldn't figure out anything to work for.


absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer

Try this...

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0

Update: Try this


inNumber = [32, 12.5, 'e', 82, 52, 92, '1224.5', '12,53',
            10000.000, '10,000459', 
           'This is a sentance, with comma number 1 and dot.', '121.124']

try:

    def find_float(num):
        num = num.split('.')
        if num[-1] is not None and num[-1].isdigit():
            return True
        else:
            return False

    for i in inNumber:
        i = str(i).replace(',', '.')
        if '.' in i and find_float(i):
            print('This is float', i)
        elif i.isnumeric():
            print('This is an integer', i)
        else:
            print('This is not a number ?', i)

except Exception as err:
    print(err)

variable.isnumeric checks if a value is an integer:

 if myVariable.isnumeric:
    print('this varibale is numeric')
 else:
    print('not numeric')

참고URL : https://stackoverflow.com/questions/4541155/check-if-a-number-is-int-or-float

반응형