LoginSignup
1
0

More than 3 years have passed since last update.

Python3で業務的なデータはDecimalで

Last updated at Posted at 2020-01-10

Python3で業務的なデータはDecimalで

プログラマ初心者の頃を思い出す、初歩的ミスをしたので
基本中の基本的なことですが反省を込めて投稿を

パーセントの変換

こんなソースで

ng.py
#パーセント変換
#99.999 % をfloatに変換する。
def convert_per(gttper:str)->float:
    m = re.match(r"[0-9]*.[0-9][0-9][0-9]", gttper)
    ret_vees_per = float(m.group(0))/100
    #print (ret_vees_per)
    #print (type(ret_vees_per))
    return ret_vees_per

これで

call.py
print(convert_per("2.200 %"))

ってやると
0.022000000000000002
になっちゃう

あれれ?
そうです。
コンピュータ内部は、2進数で管理しているから、10進数を扱うと微妙な誤差が出てしまうのです。
近似値で良い処理であれば問題ないが、金額等を扱う場合はNGですよね。

そういうわけで、Decimalに書き換えます

てな訳で

ok.py
from decimal import *

#99.999 % をDecimalに変換する。
def convert_per(gttper:str)->Decimal:
    m = re.match(r"[0-9]*.[0-9][0-9][0-9]", gttper)
    ret_vees_per = Decimal(m.group(0))/100
    #print (ret_vees_per)
    #print (type(ret_vees_per))
    return ret_vees_per


これでOK

1
0
2

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