Python Decimal to String

后端 未结 5 1680
时光取名叫无心
时光取名叫无心 2021-02-03 18:35

There are tons of topics on here that explain how to convert a string to a decimal, but how do I convert a decimal back to a string?

Like if I did this:

         


        
5条回答
  •  被撕碎了的回忆
    2021-02-03 18:58

    Note that using the %f string formatting appears to either convert to a float first (or only output a limited number of decimal places) and therefore looses precision. You should use %s or str() to display the full value stored in the Decimal.

    Given:

    from decimal import Decimal
    foo = Decimal("23380.06198573179271708683473")
    print("{0:f}".format(foo))
    print("%s" % foo)
    print("%f" % foo)
    

    Outputs:

    23380.06198573179271708683473
    23380.06198573179271708683473
    23380.061986
    

    (ed: updated to reflect @Mark's comment.)

提交回复
热议问题