Skip to content

Python decimal to string

  • by

Use the str() function to convert decimal to string in Python. it returns a string containing a nicely printable representation of an object.

Python decimal to string example

Simple example code.

import decimal

dec = decimal.Decimal('10.0')
print(dec)
print(type(dec))

s = str(dec)
print(s)
print(type(s))

Output:

Python decimal to string

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)

Do comment if you have any doubts or suggestions on this Python converting topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *