In data formats where all base types are strings, numeric types must be converted to a standardized string format that can be compared alphabetically. For example, a value shortfor a value 27can be represented as 00027if there are no negatives.
What is the best way to present doubleas a string? In my case, I can ignore the negatives, but I would be curious how you imagine a double in any case.
UPDATE
Based on Jon Skeet's suggestion, I now use this, although I am not 100% sure that it will work correctly:
static readonly string UlongFormatString = new string('0', ulong.MaxValue.ToString().Length);
public static string ToSortableString(this double n)
{
return BitConverter.ToUInt64(BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(n)), 0).ToString(UlongFormatString);
}
public static double DoubleFromSortableString(this string n)
{
return BitConverter.Int64BitsToDouble(BitConverter.ToInt64(BitConverter.GetBytes(ulong.Parse(n)), 0));
}
UPDATE 2
I confirmed that John suspected that negatives did not work using this method. Here is a sample code:
void Main()
{
var a = double.MaxValue;
var b = double.MaxValue/2;
var c = 0d;
var d = double.MinValue/2;
var e = double.MinValue;
Console.WriteLine(a.ToSortableString());
Console.WriteLine(b.ToSortableString());
Console.WriteLine(c.ToSortableString());
Console.WriteLine(d.ToSortableString());
Console.WriteLine(e.ToSortableString());
}
static class Test
{
static readonly string UlongFormatString = new string('0', ulong.MaxValue.ToString().Length);
public static string ToSortableString(this double n)
{
return BitConverter.ToUInt64(BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(n)), 0).ToString(UlongFormatString);
}
}
:
09218868437227405311
09214364837600034815
00000000000000000000
18437736874454810623
18442240474082181119
, , .
3
. , !