Link to home
Start Free TrialLog in
Avatar of AlHal2
AlHal2Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Create BigDecimal Type in C#

I saw this method of creating a BigDecimal in C# here.  It only works for multiplication.  Could someone extend it to work for Division, Addition, Subtraction and possibly exponentiation eg finding square root of a bigDecimal?
The code is here. https://stackoverflow.com/questions/4523741/arbitrary-precision-decimals-in-c-sharp/4524254#4524254

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

Open in new window


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." : ".");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AlHal2

ASKER

What about exponentiation?  I'm thinking of using this for the binomial distribution, so need to multiply very large numbers by decimals raised to powers.
The very large numbers need big integers.  The decimals and powers can be normal decimals.  The result needs to be a large rational.
Avatar of AlHal2

ASKER

Thanks.