A Tricky

Looking for an easy way to convert values of datatype double to

strings?

You might think you can just set a String object equal to a double

value, like this...

Double dow = 9845.39;

String convertedDouble = dow;

...but you can't. The Java compiler doesn't allow you to assign Strings

equal to doubles.

You might also try to apply the toString() method, like this:

Double dow = 9845.39;

System.out.println(dow.toString());

That's invalid as well. It reflects confusion with the double datatype

with the Double object. They're not the same thing, and the double type

does not support the toString() method.

You can solve the problem this way:

Double dow = 9845.39;

String convertedDouble = new String();

convertedDouble.valueOf(dow);

That's simple enough if you think for a second, but a task as simple as

this one shouldn't require you to think at all. You might try it this

way:

Double dow = 9845.39;

String convertedDouble = ("" + dow)

The string concatenation with the plus operator forces conversion of

the double variable to a string, even though you're adding a null

string to it. Pretty sneaky, eh? It's an idea from Cay Horstmann, who

published it on Usenet in a different form.

Here's a class I wrote to illustrate the problem.

public class DoubleConverter

{

public static void main(String[] args)

{

double dow = 9845.39;

System.out.println(dow);

// The following line won't compile.

// String convertedDouble = dow;

// This one won't, either.

// System.out.println(dow.toString());

// This works, but it's a pain to write:

String convertedDouble1 = new String();

convertedDouble1.valueOf(dow);

System.out.println(convertedDouble1);

// This is much more straightforward:

String convertedDouble2 = ("" + dow)

System.out.println(convertedDouble2);

}

}

Don't forget to keep working on your Outlook Express message de-

duplicators! Competition promises to be fierce this time.

Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies