Arbitrary-Precision Decimals in C# [duplicate]

元气小坏坏 提交于 2019-11-26 17:57:44
Merlyn Morgan-Graham

Big Decimal:

Big Int (If you like J.D.'s solution, or want to come up with a rational number/fraction type class. That, and I somehow missed that you were looking for decimals, not ints):

You could implement your own based on .NET 4.0's BigInteger class. I did this for fun, it does multiplication only:

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

There's always the GNU MP wrapper for .NET as long as you don't mind using the GMP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!