Emily
Emily

Reputation: 2331

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?

Upvotes: 10

Views: 2243

Answers (3)

mkrieger1
mkrieger1

Reputation: 23142

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)

Upvotes: 14

Fomalhaut
Fomalhaut

Reputation: 9727

If I understand you correctly you can use divmod (it's a build-in function). It splits a number into integer and decimal parts:

>>> import decimal
>>> d1 = decimal.Decimal(3.14)
>>> divmod(d1, 1)[0]
Decimal('3')
>>> d2 = decimal.Decimal(5.64)
>>> divmod(d2, 1)[0]
Decimal('5')

Upvotes: 0

Willis Blackburn
Willis Blackburn

Reputation: 8204

To cut off decimals past (for example) the second decimal place:

from math import floor
x = 3.14159
x2 = floor(x * 100) / 100

Upvotes: -1

Related Questions