Answer a question

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?

Answers

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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐