Skip to content

Python quantize() Function

  • by

Python quantize() Function return a value equal to the first operand after rounding and having the exponent of the second operand.

Decimal.quantize(value)

Python quantize() function example

Simple example code.

from decimal import *

# decimal value
a = Decimal(-1)
b = Decimal('0.142857')

print(a)
print(b)

# Decimal.quantize()
print(a.quantize(b))

print(b.quantize(b))

Output:

Python quantize() Function

list.append(decimal)

The method lists the decimal value and limits the decimal point to ‘1.00’ through quantize().

from decimal import Decimal

list1 = list()
list1.append((Decimal(2.10).copy_negate().quantize(Decimal('1.00')),
Decimal(1.3).copy_sign(Decimal(1.3)).quantize(Decimal('1.00')),
Decimal(3).exp().quantize(Decimal('1.00'))))
print("The items in the list1 are:,", list1)

Output: The items in the list1 are:, [(Decimal(‘-2.10’), Decimal(‘1.30’), Decimal(‘20.09’))]

How to define a rounding scale for Decimal.quantize?

Answer: Unlike binary floating-point, decimal instances have a concept of significant trailing zeroes, and it’s only the internal exponent quantize() uses.

from decimal import Decimal, ROUND_HALF_UP


def custom_round(dec: Decimal, scale, rounding_mode):
return dec.quantize(Decimal(scale), rounding_mode)


number_1 = Decimal("10.026")
res1 = custom_round(number_1, "1.00", ROUND_HALF_UP)
print(res1) # 10.03

Do comment if you have any doubts or suggestions on this Python function code.

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