Yahor
Yahor

Reputation: 671

Map Java double to String preserving sort order

I am looking for a method String doubleToString(double d), which satisfies the following condition:

For any pair of double d1 and d2 if Double.compare(d1, d2) < 0 then doubleToString(d1).compareTo(doubleToString(d2)) < 0.

To illustrate the need, I wrote a similar method for int type:

public static String intToString(int i) {
    String string = Integer.toHexString(i - Integer.MIN_VALUE);
    return "00000000".substring(string.length()) + string;
}

Results (every next String is greater than the previous):

intToString(-2147483648) = intToString(0x80000000) = "00000000"
intToString(-10)         = intToString(0xfffffff6) = "7ffffff6"
intToString(-1)          = intToString(0xffffffff) = "7fffffff"
intToString(0)           = intToString(0x0)        = "80000000"
intToString(1)           = intToString(0x1)        = "80000001"
intToString(10)          = intToString(0xa)        = "8000000a"
intToString(2147483647)  = intToString(0x7fffffff) = "ffffffff"

What I want is to have the same behaving method for double's.

Upvotes: 2

Views: 188

Answers (3)

user207421
user207421

Reputation: 310859

You're on the right track but you will need to provide up to 16 leading zeros for the integral part. The fractional part can be arbitrarily long so you can't just use string.length() as per your int code.

It would be better to keep the collection of doubles as doubles, or Doubles, and only convert to String for display or reporting purposes.

Upvotes: 0

Nevay
Nevay

Reputation: 794

You can convert the doubles to longs and then use a similar method like you already used for ints. I assume that the following method works as you want (NaN is treated as largest number):

public static String doubleToString(double d) {
    final long bits = Double.doubleToLongBits(d);
    final String s = Long.toString(bits);
    return (bits < 0 ? "--------------------" : "00000000000000000000").substring(s.length()) + s;
}

Example input and output:

[-Infinity, -1.7976931348623157E308, -4.9E-324, -0.0, 0.0, 4.9E-324, 1.7976931348623157E308, Infinity]
----4503599627370496
----4503599627370497
-9223372036854775807
-9223372036854775808
00000000000000000000
00000000000000000001
09218868437227405311
09218868437227405312

Upvotes: 3

Norbert
Norbert

Reputation: 254

It's never no good idea to compare numeric with its string representation.

However - to answer your question - a doubleToString(d1) is: String s = String.valueOf(d1); or simply: String s = "" + d1;

Upvotes: -1

Related Questions