1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Floatでも実質的に整数ならIntegerにする方法

Last updated at Posted at 2018-06-06

JSONを受け入れるとき、Floatで指定していたら整数で投げても.0がついてしまって、Integerで欲しいのにFloatになってしまう。なので、Floatが整数かどうかを判定して、整数ならInt型に、そうでないならFloat型のままにする方法を調べた。

汚い方法

Stringにして後ろ2文字が.0なら、整数としてみた。

num = 46.0
if str(num)[-2:] == '.0':
    num = int(num)    

汚いので、別の方法を検討。

たぶんまっとうな方法

a = 10b = 10.0のとき、a == int(b)trueになることを利用した。

num = 46.0
if num == int(num):
    num = int(num)

なるほど。

一行で書こうぜ

num = int(num) if num == int(num) else num

オブジェクトに聞いてみよう

@shiracamus 様、コメントありがとうございます!

num = int(num) if num.is_integer() else num

ちなみに・・・

a = 10b = 10.0を比較して、falseにしたいときは、、、

a == b # true
a is b # false
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?