如何将numpy.int32转换为decimal.Decimal

3
我正在使用一个库,它在函数调用中使用一些十进制参数。但是我有一个numpy.int32类型的变量。当我将它传递给函数调用时,我会得到以下错误:
``` TypeError: 不支持从numpy.float32到Decimal的转换 ```
这意味着库尝试将我的传递参数转换为decimal.Decimal,但失败了。请告诉我,在将变量传递给库之前如何进行转换。谢谢。

也许你先要将 numpy.int32 转换为 numpy.float32 - DrBwts
1个回答

3

Decimal接受原生的Python类型。

numpyType.item()返回相应的原生类型。

以下是一个示例:

import decimal
import numpy as np

# other library function
# will raise exception if passed argument is not Decimal
def library(decimal_arg):
    if type(decimal_arg) is not decimal.Decimal:
        raise TypeError('Not a decimal.Decimal')
    return decimal_arg

# wrapper with try block
def try_library(arg):
    try:
        print(library(arg))
    except TypeError as e:
        print(e)

def main():
    # we have some numpy types
    a = np.float32(1.1)
    b = np.int32(2)
    c = np.uint64(3000)

    # passing the numpy type does not work
    try_library(a)

    # Decimal's constructor doesn't know conversion from numpy types
    try:
        try_library(decimal.Decimal(a))
    except TypeError as e:
        print(e)

    # calling a.item() will return native Python type
    # constructor of Decimal accepts a native type
    # so it will work
    try_library(decimal.Decimal(a.item()))
    try_library(decimal.Decimal(b.item()))
    try_library(decimal.Decimal(c.item()))

main()
# output:

# Not a decimal.Decimal
# Cannot convert 1.1 to Decimal
# 1.10000002384185791015625
# 2
# 3000

@MuhammadUmarFarooq 如果我的回答解决了你的问题,你可能想要接受我的答案。如果没有,请在下面评论并指出我应该改进哪些部分或需要更多解释的部分。 - sanitizedUser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接