C#中的任意精度小数

时间:2010-12-24 01:50:28

标签: c# math decimal precision j#

  

可能重复:
  Big integers in C#
  C# unlimited significant decimal digits (arbitrary precision) without java

我在Arbitrary precision decimals in C#?读到了这个问题,但我没有J#库。我需要一个带有C#的任意精度小数的库。

3 个答案:

答案 0 :(得分:11)

您可以基于.NET 4.0的BigInteger类实现自己的。我这样做是为了好玩,它只做乘法:

public struct BigDecimal {
    public BigInteger Integer { get; set; }
    public BigInteger Scale { get; set; }

    public BigDecimal(BigInteger integer, BigInteger scale) : this() {
        Integer = integer;
        Scale = scale;
        while (Scale > 0 && Integer % 10 == 0) {
            Integer /= 10;
            Scale -= 1;
        }
    }

    public static implicit operator BigDecimal(decimal a) {
        BigInteger integer = (BigInteger)a;
        BigInteger scale = 0;
        decimal scaleFactor = 1m;
        while ((decimal)integer != a * scaleFactor) {
            scale += 1;
            scaleFactor *= 10;
            integer = (BigInteger)(a * scaleFactor);
        }
        return new BigDecimal(integer, scale);
    }

    public static BigDecimal operator *(BigDecimal a, BigDecimal b) {
        return new BigDecimal(a.Integer * b.Integer, a.Scale + b.Scale);
    }

    public override string ToString() {
        string s = Integer.ToString();
        if (Scale != 0) {
            if (Scale > Int32.MaxValue) return "[Undisplayable]";
            int decimalPos = s.Length - (int)Scale;
            s = s.Insert(decimalPos, decimalPos == 0 ? "0." : ".");
        }
        return s;
    }
}

...

decimal d1 = 254727458263237.1356246819m;
decimal d2 = 991658834219519273.110324m;
// MessageBox.Show((d1 * d2).ToString()); // OverflowException
BigDecimal bd1 = d1;
BigDecimal bd2 = d2;
MessageBox.Show((bd1 * bd2).ToString()); // 252602734305022989458258125319270.5452949161059356

答案 1 :(得分:3)

大十进制:

Big Int(如果你喜欢J.D.的解决方案,或想要提出一个有理数/分数类型。那,我错过了你在寻找小数,而不是整数):

答案 2 :(得分:3)

只要你不介意使用GNU MP wrapper for .NET,总会有GMP