ユーニックス総合研究所

  • home
  • archives
  • python-int-float

Pythonのint, floatの使い方: オブジェクトの数値変換

  • 作成日: 2021-06-10
  • 更新日: 2023-12-24
  • カテゴリ: Python

Pythonのint, floatの使い方

Pythonにはintfloatという関数があります。
これらの関数を使うと文字列などのオブジェクトを数値に変換することが可能です。

結論から言うとint()float()を使った数値変換は↓のようにやります。

n = int('1')  
print(n)  
# 1  

n = float('3.14')  
print(n)  
# 3.14  

この記事では具体的に↓を見ていきます。

  • int()でオブジェクトを整数に変換
  • float()でオブジェクトを実数に変換

int()でオブジェクトを整数に変換

int()について最初に見てみます。

int()の構造

int()は↓のような構造を持っています。

class int(x, base=10)  

int()は組み込み関数に分類されてますが、その実体はクラスです。
第1引数のxには数値、文字列, bytes, bytearrayのいずれかのオブジェクトを指定できます。
第2引数のbaseが与えられた場合、これらはbaseを基数にした整数リテラルで表されたものである必要があります。

int()は第1引数xを変換できなかった場合は例外ValueErrorを送出します。

int()を単体で呼び出し

int()を単体で呼び出すと0を得ることができます。

n = int()  
print(n)  
# 0  

int()で実数を整数に変換

int()で浮動小数点数を整数に変換するには↓のようにコードを書きます。

n = int(3.14)  
print(n)  
# 3  

int()で文字列を数値に変換

int()で文字列を数値に変換するには↓のようにコードを書きます。

n = int('1')  
print(n)  
# 1  

n = int('    -123    ')  
print(n)  
# -123  

int()でバイト列を数値に変換

int()でバイト列を数値に変換するには↓のようにコードを書きます。

n = int(b'12')  
print(n)  
# 12  

int()でbytearrayを数値に変換

int()bytearrayを数値に変換するには↓のようにコードを書きます。

arr = bytearray(b'123')  
n = int(arr)  
print(n)  
# 123  

int()の例外補足

int()は第1引数を数値に変換できなかった場合はValueErrorを送出します。
この例外を補足してリカバリーできるようにしておく必要があります。

try:  
    int('abc')  
except ValueError as e:  
    print(e)  
    # invalid literal for int() with base 10: 'abc'  

また、第1引数が未対応のタイプだった場合は例外TypeErrorを送出します。

try:  
    int(None)  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'NoneType'  

float()でオブジェクトを実数に変換

float()について見てみます。

float()の構造

float()は↓のような構造になっています。

class float([x])  

float()は第1引数のxを浮動小数点数に変換します。
xは数値、文字列、バイト列、bytearrayのいずれかになります。

この第1引数xのフォーマットを表すBNF(文法)は↓のようなものです。

sign           ::=  "+" | "-"  
infinity       ::=  "Infinity" | "inf"  
nan            ::=  "nan"  
numeric_value  ::=  floatnumber | infinity | nan  
numeric_string ::=  [sign] numeric_value  

↑の場合numeric_stringが引数xです。
これは0個以上のsignnumeric_valueで構成されます。
sign+-のどちらかです。
numeric_valueは実数か、Infinity, inf, nanのいずれかになります。
Infinityなどは大文字(INFINITYなど)でもOKです。

引数xが浮動小数点数の範囲外であれば例外OverflowErrorが送出されます。

float()を単体で呼び出し

float()を単体で呼び出すと0.0が得られます。

n = float()  
print(n)  
# 0.0  

float()で整数を実数に変換

float()に整数を渡すと浮動小数点数に変換できます。

n = float(123)  
print(n)  
# 123.0  

float()で文字列を実数に変換

float()で文字列を実数に変換するには↓のようにコードを書きます。

n = float('3.14')  
print(n)  
# 3.14  

n = float('   -1.23   ')  
print(n)  
# -1.23  

float()でバイト列を実数に変換

float()でバイト列を浮動小数点数に変換するには↓のようにコードを書きます。

n = float(b'3.14')  
print(n)  
# 3.14  

float()でbytearrayを実数に変換

float()bytearrayを浮動小数点数に変換するには↓のようにコードを書きます。

arr = bytearray(b'3.14')  
n = float(arr)  
print(n)  
# 3.14  

Infinity, nanなど

Infinitynanなどは↓のように変換されます。

print(float('infinity'))  # inf  
print(float('INFINITY'))  # inf  
print(float('inf'))  # inf  
print(float('INF'))  # inf  
print(float('nan'))  # nan  
print(float('NAN'))  # nan  
print(float('+infinity'))  # inf  
print(float('-INFINITY'))  # -inf  

float()の例外補足

float()は第1引数を数値に変換できなかった場合はint()と同様にValueErrorを送出します。

try:  
    float('abc')  
except ValueError as e:  
    print(e)  
    # could not convert string to float: 'abc'  

また、第1引数が未対応のタイプだった場合は例外TypeErrorを送出します。

try:  
    float(None)  
except TypeError as e:  
    print(e)  
    # float() argument must be a string or a number, not 'NoneType'  

巨大な整数を渡した場合などは例外OverflowErrorが送出されます。

try:  
    float(2 ** 10000)  
except OverflowError as e:  
    print(e)  
    # int too large to convert to float  

おわりに

今回はPythonのint()float()について見てみました。
これらは組み込み関数なので使いたい時にすぐ使えますね。

🦝 < 整数と実数を扱う者よ・・・

🐭 < はい・・・

🦊 < 特にオチはないのか・・・