views:

974

answers:

5

I would like to replace "." by "," in a String/double that I want to write to a file.

Using the following Java code

double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);

String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);

myDoubleString.replace(".", ",");
System.out.println(myDoubleString);

myDoubleString.replace('.', ',');
System.out.println(myDoubleString);

I get the following output

38.1882352941176
38.1882352941176
38.1882352941176
38.1882352941176

Why isn't replace doing what it is supposed to do? I expect the last two lines to contain a ",".

Do I have to do/use something else? Suggestions?

+7  A: 

You need to make your string actually equal the changes you make to the string or they are lost.

double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);

String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);

myDoubleString = myDoubleString.replace(".", ",");
System.out.println(myDoubleString);

myDoubleString = myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
AlbertoPL
As usual the problem sits in front of the computer ;-) Thx
CL23
The reason it returns a new string is that Strings are immutable in Java.
R. Bemrose
PEBKAC - Problem Exists Between Keyboard And Chair. :-P
Jack Leow
+3  A: 
Chris Kessel
+1  A: 

replace returns a new String (since String is immutable in Java):

String newString = myDoubleString.replace(".", ",");
dfa
+2  A: 

Always remember, Strings are immutable. They can't change. If you're calling a String method that changes it in some way, you need to store the return value. Always.

I remember getting caught out with this more than a few times at Uni :)

Cosmic Flame
+2  A: 

The bigger question is why not use DecimalFormat instead of doing String replace?

http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html

vh
Very good point! Your answer goes beyond my question, but solves the problem that I essentially had. I didn't know DecimalFormat, thanks!
CL23