Skip to content

Instantly share code, notes, and snippets.

@tomtheisen
Created August 30, 2019 15:57
Show Gist options
  • Save tomtheisen/0b059caf2889fe54dacfb08ba5d3cf2a to your computer and use it in GitHub Desktop.
Save tomtheisen/0b059caf2889fe54dacfb08ba5d3cf2a to your computer and use it in GitHub Desktop.
Precise ToString() for double
using static System.Double;
using static System.Math;
using static System.Numerics.BigInteger;
using System.Numerics;
public static class DoubleConvert {
public static string Precisely(this double a) {
if (IsInfinity(a) || IsNaN(a)) return a.ToString();
if (a == 0) return 1 / a < 0 ? "-0.0" : "0.0";
BigInteger n = 0, d = 1, p = 1;
string r = a < 0 ? "-" : "";
for (a = Abs(a); a < 0.5; a *= 2) d *=2;
for (; a >= 1; a /= 2) p *= 2;
for (; a > 0; a %= 1, d *= 2) n = n * 2 + p * (int)(a *= 2);
r += DivRem(n, d, out n) + ".";
do r += DivRem(n * 10, d, out n); while (n > 0);
return r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment