I'm curious to know if you could convert decimal
to double
, but still be able to come back to the same decimal
I started with. Of course, assuming you use 15 or less significant digits. Basically, can you count on this:
decimal original = someValue;
double converted = ReversibleToDouble(original);
decimal result = BackToDecimal(converted);
if (original == result)
Console.WriteLine("All is well with the world.");
I don't mind if ReversibleToDouble
threw an exception or something if there is no such conversion, as long as the result is guaranteed upon successful completion. Right now, this is the trivial solution I have:
public static double ReversibleToDouble(decimal input)
{
double output = (double)input;
if ((decimal)output != input)
throw new ArgumentException("Impossible to convert reversibly.", "input");
return output;
}
public static decimal BackToDecimal(double input)
{
return (decimal)input;
}
I don't really know much about numerical analysis so I have a couple of questions about this.
First question: is this trivial method guaranteed to work without raising exceptions if there are less than 15 significant digits before trying any conversions?
If not, second question: is there a way to make this work with greater probability?
If yes, one last question: is this doable without majoring in a field of science? :)