Skip to content

Convert float to decimal Python

  • by

Just pass the float to the Decimal constructor to Convert the float to decimal in Python. Or you can use round(value,2) to return a floating-point number up to two decimal places.

from decimal import Decimal
Decimal(f)

Convert float to decimal Python example

Simple example code.

from decimal import Decimal

f = 123.5
a = Decimal(f)

print(type(f))
print(a)
print(type(a))

Output:

Convert float to decimal Python

How to convert float to fixed point decimal in Python

Answer: Use Decimal.quantize:

from decimal import Decimal

print(Decimal(50.15))
print(Decimal(50.15).quantize(Decimal('1.00')))

Do comment if you have any doubts or suggestions on this Python conversation 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading