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?
 
Shaun VermaakTechnical Specialist/DeveloperCommented:
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.