我想像这样将一个 Biginteger 乘以一个 double
buyableObjects[index - 1].cost = buyableObjects[index - 1].cost * BigInteger.Pow((BigInteger)multiplier, buyableObjects[index - 1].indexMultiplier);
问题是 multiplier 是一个等于 1.15 的双精度值,而 BigInteger 忽略了 0.15。有没有办法将我的对象的成本(也是一个 Biginteger 值)乘以 double 值 1.15 并将其四舍五入为一个 biginteger?
您可以乘以 115,然后除以 100。
我们可以看到 here BigInteger.Pow() 接受一个 BigInteger 后跟一个常规的 Base 32 整数。因此,如果您只想使用双精度数,我不明白您为什么要使用 BigInteger.Pow() 函数。
因为我们知道 multiplier 是一个 double 而 buyableObjects[index-1].indexMultiplier 是一个整数, 我会做
double finalMultiplier = Math.Pow(multiplier, buyableObjects[index-1].indexMultiplier);
然后你只需要面对将 BigInteger 乘以 double 的问题,你可以通过将其分解为乘法和除法来解决。
比如说 finalMultiplier = 2.27;此时您可能需要进行一些舍入,因为我们不确定 finalMultiplier 的小数位数。您可以使用 Math.Round() 函数实现此目的。 例如:
int decimalPlaces = 2;
double finalMultiplier = 2.225f;
finalMultiplier = Math.Round(finalMultiplier,decimalPlaces, MidpointRounding.ToEven);
//Will round 2.225 to 2.22
BigInteger cost = new BigInteger(500);
cost *= ((BigInteger) (finalMultiplier * Math.Pow(10, decimalPlaces))); //Multiply by 222
cost /= (BigInteger) (Math.Pow(10,decimalPlaces)); //Divide by 100
print(cost); //1110
public static class BigIntegerHelper
{
public static BigInteger MultiplyByDouble(this BigInteger x, double y)
{
BigInteger result = 0;
double accumulatingRemainder = 0;
for (var tensExp = 0; tensExp < 19; tensExp++)
{
var trimmed = (long)y;
var unshifted = trimmed * x;
var shifter = (long)Math.Pow(10, tensExp);
accumulatingRemainder += (double)(unshifted % shifter) / shifter;
result += unshifted / shifter;
y = (y - trimmed) * 10;
}
return result + (long)(accumulatingRemainder + 0.5);
}
}
像这样使用它:
var answer = myBigIntegerVariable.MultiplyByDouble(myDoubleVariable);