简体   繁体   English

如何从 Decimal 类型的 Python 变量中获取前十进制和小数位?

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

Let's say I've a variable var = Decimal('3.5685') .假设我有一个变量var = Decimal('3.5685') How can I get the pre-decimal places ( 3 ) and the decimal places ( 5685 ) from it?如何从中获得小数位前 ( 3 ) 和小数位 ( 5685 )?

int(var) will give you the integer part (as an integer); int(var)会给你整数部分(作为整数); from as_tuple you can get the fractional part (as a tuple):as_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.您可以根据需要使用结果变量predecimalpostdecimal

If you want to get an integer instead of a string just split like this instead:如果你想得到一个整数而不是一个字符串,只需像这样拆分:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM