我想把一个大整数乘以一个双精度数,如下所示
buyableObjects[index - 1].cost = buyableObjects[index - 1].cost * BigInteger.Pow((BigInteger)multiplier, buyableObjects[index - 1].indexMultiplier);问题是乘数是一个等于1.15的双精度值,而BigInteger忽略了0.15。是否有办法将我的对象的成本乘以双精度值1.15,并将其四舍五入为大整数?
发布于 2019-11-14 01:52:44
我们可以看到here BigInteger.Pow()接受一个BigInteger,后跟一个标准的32位整数。因此,如果您只打算使用double,我就不明白为什么要使用BigInteger.Pow()函数。
因为我们知道multiplier是一个双精度的,而buyableObjectsindex-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); //1110Here提供了一些关于C#中不同舍入模式的信息。这样做将帮助你指定如何进行舍入,我已经向你展示了如何实现其他人所说的一些关于分解小数点的东西。我会让你自由地替换正确的变量,但希望这会有所帮助!你所要做的就是用你的BigInteger替换cost,并使用我在那里提供的finalMultiplier。你可以随心所欲地定制decimalPlaces。
发布于 2019-11-14 01:20:03
相反,你可以乘以115,然后除以100。
https://stackoverflow.com/questions/58841947
复制相似问题