栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#中有BigFloat类吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#中有BigFloat类吗?

也许您在寻找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,就像十进制或双精度一样。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416816.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号