I need to truncate decimal types without rounding & retain the decimal type, in the most processor efficient way possible.
The Math options I believe returns a float.
The quantize option returns a rounded number I believe.
Str options are way to processor costly.
Is there a simple, direct way to simply cut the digits off a decimal type past a specified decimal length?
The quantize
method does have a rounding
parameter which controls how the value is rounded. The ROUND_DOWN
option seems to do what you want:
ROUND_DOWN
(towards zero)
from decimal import Decimal, ROUND_DOWN
def truncate_decimal(d, places):
"""Truncate Decimal d to the given number of places.
>>> truncate_decimal(Decimal('1.234567'), 4)
Decimal('1.2345')
>>> truncate_decimal(Decimal('-0.999'), 1)
Decimal('-0.9')
"""
return d.quantize(Decimal(10) ** -places, rounding=ROUND_DOWN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With