Python Decimal to String

后端 未结 5 1738
时光取名叫无心
时光取名叫无心 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:53

    Almost all the built-ins work on the Decimal class as you would expect:

    >>> import decimal
    >>> dec=decimal.Decimal('10.0')
    

    A string:

    >>> str(dec)
    '10.0'
    

    A float:

    >>> float(dec)
    10.0
    

    An int:

    >>> int(dec)
    10
    

    Object representation (as it would be in the interactive interpreter):

    >>> repr(dec)
    "Decimal('10.0')"
    

    Rational number:

    >>> import fractions
    >>> fractions.Fraction(decimal.Decimal('0.50'))
    Fraction(1, 2)
    

提交回复
热议问题