C#中有BigFloat类吗?

jb.*_*jb. 9 c# numeric bigfloat

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

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

System.Numerics.BigInteger big = maxint * maxint * maxint;
System.Console.WriteLine(big);
Run Code Online (Sandbox Code Playgroud)

Chr*_*ens 18

也许你在寻找BigRational?微软在CodePlex的BCL项目下发布了它.实际上并不确定它是否符合您的需求.

它使它成为一个有理数.您可以通过强制转换或一些乘法来获取带小数值的字符串.

var r = new BigRational(5000, 3768);
Console.WriteLine((decimal)r);
Console.WriteLine((double)r);
Run Code Online (Sandbox Code Playgroud)

或者使用这样的简单(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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果它超出了小数或双精度范围,它们将被转换为各自的类型,其值为0.0.此外,当结果超出其范围时,转换为十进制将导致OverflowException抛出.

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