Created
August 30, 2019 15:57
-
-
Save tomtheisen/0b059caf2889fe54dacfb08ba5d3cf2a to your computer and use it in GitHub Desktop.
Precise ToString() for double
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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