using System.Globalization;
public static void Main()
ShowValues(316.226184874055d);
ShowValues(316.226184874055d * 1e11);
ShowValues(31622618487405d / 1e11);
ShowValues(Math.Round(316.226184874055d, 11));
public static void ShowValues(double val)
Console.WriteLine("{0} = {1}", val, DoubleConverter.ToExactString(val));
public class DoubleConverter
public static string ToExactString(double d)
if (double.IsPositiveInfinity(d))
if (double.IsNegativeInfinity(d))
long bits = BitConverter.DoubleToInt64Bits(d);
bool negative = (bits < 0);
int exponent = (int)((bits >> 52) & 0x7ffL);
long mantissa = bits & 0xfffffffffffffL;
mantissa = mantissa | (1L << 52);
while ((mantissa & 1) == 0)
ArbitraryDecimal ad = new ArbitraryDecimal(mantissa);
for (int i = 0; i < -exponent; i++)
for (int i = 0; i < exponent; i++)
return "-" + ad.ToString();
internal ArbitraryDecimal(long x)
string tmp = x.ToString(CultureInfo.InvariantCulture);
digits = new byte[tmp.Length];
for (int i = 0; i < tmp.Length; i++)
digits[i] = (byte)(tmp[i] - '0');
internal void MultiplyBy(int amount)
byte[] result = new byte[digits.Length + 1];
for (int i = digits.Length - 1; i >= 0; i--)
int resultDigit = digits[i] * amount + result[i + 1];
result[i] = (byte)(resultDigit / 10);
result[i + 1] = (byte)(resultDigit % 10);
Array.Copy(result, 1, digits, 0, digits.Length);
internal void Shift(int amount)
internal void Normalize()
for (first = 0; first < digits.Length; first++)
for (last = digits.Length - 1; last >= 0; last--)
if (first == 0 && last == digits.Length - 1)
byte[] tmp = new byte[last - first + 1];
for (int i = 0; i < tmp.Length; i++)
tmp[i] = digits[i + first];
decimalPoint -= digits.Length - (last + 1);
public override String ToString()
char[] digitString = new char[digits.Length];
for (int i = 0; i < digits.Length; i++)
digitString[i] = (char)(digits[i] + '0');
return new string(digitString);
return new string(digitString) +
new string('0', -decimalPoint);
if (decimalPoint >= digitString.Length)
new string('0', (decimalPoint - digitString.Length)) +
return new string(digitString, 0,
digitString.Length - decimalPoint) +
digitString.Length - decimalPoint,