我有一个 BigInteger cost = 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 cost = BigInteger.Parse("111111222222333333444444555555");
BigInteger costMultiply = (BigInteger)(1.1f*1000f);
BigInteger result = (cost / 1000)* costMultiply;
结果:122222344444566666788889011110
有点晚了,但我也在寻找,这最适合我