Skip to content

Instantly share code, notes, and snippets.

@ronnieoverby
Created April 21, 2017 19:30
Show Gist options
  • Save ronnieoverby/fe1a289e888c63f233cea8569ae09f3b to your computer and use it in GitHub Desktop.
Save ronnieoverby/fe1a289e888c63f233cea8569ae09f3b to your computer and use it in GitHub Desktop.
void Main()
{
var a = new BigDecimal(
BigInteger.Parse("9999999999999999999999999999999999999999999999999"), 0);
var b = new BigDecimal(
BigInteger.Parse("99999999999999999999998999999988998899999999999"),
17);
var c = a*b;
// = 9999999999999999999999899999998899889999999999899000000000000000000000010000000.11001100000000001
Console.WriteLine(c);
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment