Určenie, či je číslo celé alebo desatinné v jazyku Python.
Nasledujúce prípady sú vysvetlené pomocou vzorových kódov.
- Určuje, či je číslo celé číslo int alebo číslo s pohyblivou rádovou čiarkou float:
isinstance()
- Určuje, či je číslo typu float celé číslo (0 desatinných miest):
float.is_integer()
- Určí, či je číselný reťazec celé číslo
Ak chcete získať celočíselné a desatinné hodnoty desatinného čísla, pozrite si nasledujúci článok.
- SÚVISIACE:Získanie celočíselnej a desiatkovej časti čísla súčasne pomocou funkcie math.modf v jazyku Python
Informácie o tom, či je reťazec číslo (vrátane čínskych číslic atď.), a nie celé alebo desatinné číslo, nájdete v nasledujúcom článku.
Určuje, či je číslo typu celé číslo alebo číslo s pohyblivou rádovou čiarkou: isinstance()
Typ objektu možno zistiť pomocou vstavanej funkcie type().
i = 100
f = 1.23
print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>
isinstance(object, type)
Túto vstavanú funkciu možno použiť na určenie, či je objekt určitého typu. Pomocou tejto funkcie možno určiť, či je číslo typu celé číslo alebo číslo s pohyblivou rádovou čiarkou.
print(isinstance(i, int))
# True
print(isinstance(i, float))
# False
print(isinstance(f, int))
# False
print(isinstance(f, float))
# True
V tomto prípade posudzuje iba typ, takže nemôže posúdiť, či hodnota typu float je celé číslo (s desatinnou čiarkou 0) alebo nie.
f_i = 100.0
print(type(f_i))
# <class 'float'>
print(isinstance(f_i, int))
# False
print(isinstance(f_i, float))
# True
Určuje, či je číslo typu float celé číslo (0 desatinných miest): float.is_integer()
Pre typ float je k dispozícii metóda is_integer(), ktorá vráti true, ak je hodnota celé číslo, a false v opačnom prípade.
f = 1.23
print(f.is_integer())
# False
f_i = 100.0
print(f_i.is_integer())
# True
Napríklad funkciu, ktorá vracia true pre celé číslo, možno definovať takto Na druhej strane pre typ reťazec by sa vrátila false.
def is_integer_num(n):
if isinstance(n, int):
return True
if isinstance(n, float):
return n.is_integer()
return False
print(is_integer_num(100))
# True
print(is_integer_num(1.23))
# False
print(is_integer_num(100.0))
# True
print(is_integer_num('100'))
# False
Určí, či je číselný reťazec celé číslo
Ak chcete určiť, že reťazec celých číslic je tiež celé číslo, môžete použiť nasledujúce funkcie.
Pre hodnoty, ktoré možno previesť na typ float pomocou metódy float(), sa po prevode na float použije metóda is_integer() a vráti sa výsledok.
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
print(is_integer(100))
# True
print(is_integer(100.0))
# True
print(is_integer(1.23))
# False
print(is_integer('100'))
# True
print(is_integer('100.0'))
# True
print(is_integer('1.23'))
# False
print(is_integer('string'))
# False
Podrobnosti o konverzii reťazcov na čísla nájdete v nasledujúcom článku.
Podrobnosti o určovaní, či je reťazec číslo (vrátane čínskych číslic atď.), nájdete v nasledujúcom článku.