C#/Unity:将 BigInteger 乘以 Float
C# / Unity: Multiply BigInteger by Float
我有一个 BigInteger 成本 = 1111112222223333333444444555555 和一个 float costMultiply 1.1f。
我尝试:
newCost = cost * costMultiply
并得到“无法应用运算符“*””- 错误。
我也试过:
int multiplierBuffer = (int)(costMultiply * 10);
cost = cost * (multiplierBuffer / 10);
这不会引发错误,但会返回初始成本值(未乘以 1.1f)。
如何将 BigInteger 乘以浮点数?
您必须将 BigInteger 转换为 double/Double。
BigInteger cost = new BigInteger(10000000000000000000);
float costMultiply = 1.1f;
double dCost = (double) cost;
double result = dCost * costMultiply;
// And since you want a BigInteger at the end
BigInteger bigIntResult = new BigInteger(result);
result
的实际类型将是 Double
,因为 double
无法容纳整数。 C# 会为您处理。
这显然可以简化。
BigInteger cost = new BigInteger(10000000000000000000);
float costMultiply = 1.1f;
BigInteger bigIntResult = new BigInteger((double) cost * costMultiply);
事实是,由于数据类型的精度水平各不相同,您的数学会变得很复杂。如果您需要精确度,我不会使用这种方法。但是,既然你想用一个整数乘以一个浮点数并得到一个整数结果,我想你不会被精度问题所困扰。
我有一个 BigInteger 成本 = 1111112222223333333444444555555 和一个 float costMultiply 1.1f。
我尝试:
newCost = cost * costMultiply
并得到“无法应用运算符“*””- 错误。
我也试过:
int multiplierBuffer = (int)(costMultiply * 10);
cost = cost * (multiplierBuffer / 10);
这不会引发错误,但会返回初始成本值(未乘以 1.1f)。
如何将 BigInteger 乘以浮点数?
您必须将 BigInteger 转换为 double/Double。
BigInteger cost = new BigInteger(10000000000000000000);
float costMultiply = 1.1f;
double dCost = (double) cost;
double result = dCost * costMultiply;
// And since you want a BigInteger at the end
BigInteger bigIntResult = new BigInteger(result);
result
的实际类型将是 Double
,因为 double
无法容纳整数。 C# 会为您处理。
这显然可以简化。
BigInteger cost = new BigInteger(10000000000000000000);
float costMultiply = 1.1f;
BigInteger bigIntResult = new BigInteger((double) cost * costMultiply);
事实是,由于数据类型的精度水平各不相同,您的数学会变得很复杂。如果您需要精确度,我不会使用这种方法。但是,既然你想用一个整数乘以一个浮点数并得到一个整数结果,我想你不会被精度问题所困扰。