1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで小数点以下の桁数を1行で取得する

Last updated at Posted at 2024-03-02

Decimalクラスを使用すれば小数点以下の桁数をスマートに取得できます。

from decimal import Decimal
value = 10.1234
print(Decimal(str(value)).as_tuple().exponent) # -4を出力

桁数がマイナス値となるので絶対値に変換すれば使いやすい。

from decimal import Decimal
count_decimal_places = lambda value: abs(Decimal(str(value)).as_tuple().exponent)
print(count_decimal_places(10.1234))  # 4を出力

なぜマイナスか?

Decimalクラスにおけるexponentの値は、数値が標準形式で表された際の10のべき乗を表します。
この場合、10.1234は小数点以下4桁を持っているため、Decimal表現では10の-4乗(つまり、0.0001)を乗じることでこの数値を表します。

1
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?