假设我有以下 IronPython 脚本:
def Calculate(input):
return input * 1.21
当使用小数从 C# 调用时,此函数返回双精度:
var python = Python.CreateRuntime();
dynamic engine = python.UseFile("mypythonscript.py")
decimal input = 100m; // input is of type Decimal
// next line throws RuntimeBinderException:
// "cannot implicitly convert double to decimal"
decimal result = engine.Calculate(input);
我似乎有两个选择:
首先,我可以在 C# 方面进行转换:似乎不行,因为我可能会失去精度。
decimal result = (decimal)engine.Calculate(input);
第二种选择是在 python 脚本中使用 System.Decimal:有效,但有点污染脚本......
from System import *
def CalculateVAT(amount):
return amount * Decimal(1.21)
是否有一个简写符号 DLR,数字 1.21 应该被解释为十进制,就像我在 C# 中使用“1.21m”符号一样?或者有没有其他方法可以强制使用十进制而不是双精度?