How to truncate decimal type and save as decimal type without rounding?

I need to trim decimal types without rounding and keep the decimal type as efficient as possible for the processor.

Math parameters that I think return a float.

The quantize option returns the rounded number that I am counting.

Str parameters are an expensive process.

Is there a simple, straightforward way to simply cut digits from a decimal type to a given decimal length?

+5
source share
4 answers

quantize has a rounding parameter that controls the rounding of the value. The ROUND_DOWN option seems to do what you want:

  • ROUND_DOWN (to 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) 
+7
source

If you have decimal for example

 num = Decimal('3.14159261034899999') 

You can do:

 getcontext().prec = 13 # set the precision (no. of digits) getcontext().rounding = ROUND_DOWN # this will effectively truncate num *= 1 

Using this, you will get ( print(num) ):

 3.141592610348 
+1
source

To trim decimals that have passed (for example) the second decimal place:

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

If you understand correctly, you can use divmod (this is a built-in function). It breaks the 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') 
0
source

Source: https://habr.com/ru/post/1262469/


All Articles