在C#中有BigFloat类吗?

System.Numerics.BigInteger可以将大整数相乘,但浮点数是否有相同的types? 如果没有,我可以使用免费的图书馆吗?

 //this but with floats System.Numerics.BigInteger maxint = new BigInteger(int.MaxValue); System.Numerics.BigInteger big = maxint * maxint * maxint; System.Console.WriteLine(big); 

也许你正在寻找BigRational ? 微软在CodePlex上的BCL项目下发布了它。 实际上并不确定如何或是否能满足您的需求。

它保持它作为一个理性的数字。 你可以通过强制转换或乘法来得到一个十进制值的string。

 var r = new BigRational(5000, 3768); Console.WriteLine((decimal)r); Console.WriteLine((double)r); 

或者用这样一个简单的(ish)扩展方法:

 public static class BigRationalExtensions { public static string ToDecimalString(this BigRational r, int precision) { var fraction = r.GetFractionPart(); // Case where the rational number is a whole number if(fraction.Numerator == 0 && fraction.Denominator == 1) { return r.GetWholePart() + ".0"; } var adjustedNumerator = (fraction.Numerator * BigInteger.Pow(10, precision)); var decimalPlaces = adjustedNumerator / fraction.Denominator; // Case where precision wasn't large enough. if(decimalPlaces == 0) { return "0.0"; } // Give it the capacity for around what we should need for // the whole part and total precision // (this is kinda sloppy, but does the trick) var sb = new StringBuilder(precision + r.ToString().Length); bool noMoreTrailingZeros = false; for (int i = precision; i > 0; i--) { if(!noMoreTrailingZeros) { if ((decimalPlaces%10) == 0) { decimalPlaces = decimalPlaces/10; continue; } noMoreTrailingZeros = true; } // Add the right most decimal to the string sb.Insert(0, decimalPlaces%10); decimalPlaces = decimalPlaces/10; } // Insert the whole part and decimal sb.Insert(0, "."); sb.Insert(0, r.GetWholePart()); return sb.ToString(); } } 

如果超出了十进制或双精度的精度范围,则会将其转换为值为0.0的相应types。 此外,如果结果超出其范围,则将其转换为十进制,将导致引发OverflowException

我写的扩展方法(可能不是计算分数的十进制表示的最佳方法)将精确地将其转换为string。 但是,如果数字小于请求的精度,它将返回0.0,就像十进制或双精度。