How can I get the pre-decmial and decimal places from a Python variable of type Decimal?

Viewed 83

Let's say I've a variable var = Decimal('3.5685'). How can I get the pre-decimal places (3) and the decimal places (5685) from it?

2 Answers

int(var) will give you the integer part (as an integer); from as_tuple you can get the fractional part (as a tuple):

from decimal import Decimal

var = Decimal('3.5685')
print(int(var))  # 3 

tpl = var.as_tuple()  # DecimalTuple(sign=0, digits=(3, 5, 6, 8, 5), exponent=-4)
print(tpl.digits[tpl.exponent:])  # (5, 6, 8, 5)

you may need to bring the tuple in the form you prefer.

Simple and short solution:

split = str(var).split('.')
predecimal = split[0]
postdecimal = split[1]

You can use the resulting variables predecimal and postdecimal however you wish.

If you want to get an integer instead of a string just split like this instead:

split = int(str(var).split('.'))
Related