2020/07/27

Pythonで小数点を含むフォーマット関数のTipsです

python

概要

Pythonの簡単なTipsです。

以下のようなフォーマットができるような関数を作成しました

  • 小数点が存在する場合だけ小数点を表示する
  • 最大N桁までサポートする

例)以下のような感じです。

  • 123 -> 123
  • 123.1 -> 123.1
  • 123.04 -> 123.04
  • 123.0012 -> 123

実装内容

2桁までサポートする場合の例です。

def float_format(f: float) -> str:
    return ("%.2f" % f).rstrip("0").rstrip(".")

float_format(123.0)
'123'

float_format(123.1)
'123.1'

float_format(123.04)
'123.04'

float_format(123.0012)
'123'

以上になります。