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

AlHal2Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun VermaakTechnical SpecialistCommented:
Can you not use the BigRational library?
//   Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using Numerics;
using System.Numerics;

namespace SampleBigRationalProgram
{
    enum RationalField
    {
        FirstNumerator,
        FirstDenominator,
        SecondNumerator,
        SecondDenominator
    };

    enum RationalOperator
    {
        Add,
        Subtract,
        Multiply,
        Divide,
        LeastCommonDenominator
    };

    class Program
    {
        // simple demo which reads in two rationals and an operator then prints the result
        static void Main(string[] args)
        {
            ConsoleProlog();
            while (true)
            {
                BigInteger numA = GetNumber(RationalField.FirstNumerator);
                BigInteger numB = GetNumber(RationalField.FirstDenominator);
                BigInteger numC = GetNumber(RationalField.SecondNumerator);
                BigInteger numD = GetNumber(RationalField.SecondDenominator);
                BigRational rational1 = new BigRational(numA, numB);
                BigRational rational2 = new BigRational(numC, numD);

                RationalOperator op = GetOperator();
                PerformOperationAndShowResult(rational1, rational2, op);
            }
        }

        static void ConsoleProlog()
        {
            Console.WriteLine("Microsoft (R) SampleBigRationalProgram.  Version 1.0.00000.0");
            Console.WriteLine("Copyright (c) Microsoft Corporation.  All rights reserved.");
            Console.WriteLine();
            Console.WriteLine("Press control+C to terminate the demo at any time.");
            Console.WriteLine();
        }

        static BigInteger GetNumber(RationalField field)
        {
            string fieldString;
            switch (field)
            {
                case RationalField.FirstNumerator:
                    fieldString = "first numerator:    ";
                    break;
                case RationalField.FirstDenominator:
                    fieldString = "first denominator:  ";
                    break;
                case RationalField.SecondNumerator:
                    fieldString = "second numerator:   ";
                    break;
                case RationalField.SecondDenominator:
                    fieldString = "second denominator: ";
                    break;
                default:
                    throw new InvalidOperationException();
            }
            Console.Write("Enter the {0} ", fieldString);
            
            string input = Console.ReadLine();
            BigInteger result;
            if (!BigInteger.TryParse(input, out result))
            {
                Console.WriteLine("Error: unable to parse value.  Defaulting to one (1) for the demo.");
                result = BigInteger.One;
            }
            return result;
        }

        static RationalOperator GetOperator()
        {
            string op;
            Console.Write("Enter the operator [+, -, *, /, lcd]: ");
            op = Console.ReadLine().ToLowerInvariant();

            switch (op)
            {
                case "+":
                    return RationalOperator.Add;
                case "-":
                    return RationalOperator.Subtract;
                case "*":
                    return RationalOperator.Multiply;
                case "/":
                    return RationalOperator.Divide;
                case "lcd":
                    return RationalOperator.LeastCommonDenominator;
                default:
                    Console.WriteLine("Error: unknown operator, defaulting to addition (+) for the demo.");
                    return RationalOperator.Add;
            }
        }

        static void PerformOperationAndShowResult(BigRational x, BigRational y, RationalOperator op)
        {
            switch (op)
            {
                case RationalOperator.Add:
                    Console.WriteLine("{0} + {1} = {2}", x, y, x + y);
                    break;
                case RationalOperator.Divide:
                    Console.WriteLine("{0} / {1} = {2}", x, y, x / y);
                    break;
                case RationalOperator.LeastCommonDenominator:
                    Console.WriteLine("LeastCommonDenominator({0}, {1}) = {2}", x, y, BigRational.LeastCommonDenominator(x, y));
                    break;
                case RationalOperator.Multiply:
                    Console.WriteLine("{0} * {1} = {2}", x, y, x * y);
                    break;
                case RationalOperator.Subtract:
                    Console.WriteLine("{0} - {1} = {2}", x, y, x - y);
                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
    }
}

Open in new window

https://github.com/MicrosoftArchive/bcl/blob/master/Libraries/BigRational/SampleBigRationalProgram/SampleBigRationalProgram/Program.cs
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlHal2Author Commented:
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.
0
AlHal2Author Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.