Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate decimal type & preserve as decimal type without rounding?

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?

like image 691
Emily Avatar asked Jan 07 '17 16:01

Emily


Video Answer


1 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)
like image 138
mkrieger1 Avatar answered Sep 19 '22 03:09

mkrieger1