也许您在寻找BigRational吗?Microsoft在其CodePlex的BCL项目下发布了它。实际不确定如何或是否会满足您的需求。
它保持为有理数。您可以通过强制转换或某种乘法来获得带有十进制值的字符串。
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。另外,当结果超出其范围时,强制转换为小数将导致
OverflowException抛出。
我编写的扩展方法(这可能不是计算分数的十进制表示的 最佳
方法)将以无限的精度将其准确转换为字符串。但是,如果数字小于要求的精度,则它将返回0.0,就像十进制或双精度一样。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)