How can i concatenate Double
to String
in java?
I have following piece of code:
Double price = 5.34;
String trade = MSFT;
now I have String key = price + trade
, not sure if this is right way of doing it, any suggestions?
How can i concatenate Double
to String
in java?
I have following piece of code:
Double price = 5.34;
String trade = MSFT;
now I have String key = price + trade
, not sure if this is right way of doing it, any suggestions?
Java string concatenation is done by default with the +
sign.
But there are times when this is not a good practice since this will create a new string instance every time you do it, so if you are in a loop this will create a new string in memory for each iteration.
So for simple cases, the +
is perfectly valid.
For other cases, you should use StringBuilder.
I would perhaps use String.format() and you'll be able to control the formatting of the double in the string. e.g. you can control leading zeros, number of dps displayed etc.
See this SO answer for examples. And here's the doc for the underlying Formatter, and the standard tutorial.
You can use String.valueOf(price)
to convert. So you'd have
Double price = 5.34;
String trade = MSFT;
String key = String.valueOf(price) + trade;
To format the string - http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
An example of how to use it.
http://www.tech-recipes.com/rx/1326/java-decimal-format-to-easily-create-custom-output/
To output it, use the + operand. This creates another string if you're looking for performance. You can also use string builder - http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html.
You can also convert your Double with a toString().
Double price = 5.34;
String trade = MSFT;
String key = Double.toString(price) + trade;
Here is the detail for the toSting() method: http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#toString(double)
But using a StringBuffer is more efficient.
Regards, Dekx.
There is nothing wrong with String key = price + trade
. It is much more readable than String.valueOf(price) + trade
or using StringBuilder
.