15

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?

CL23
  • 766
  • 2
  • 7
  • 12

5 Answers5

20

You need to assign the new value back to the variable.

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);
Joe
  • 44,558
  • 31
  • 143
  • 235
AlbertoPL
  • 11,426
  • 5
  • 45
  • 73
11

The original String isn't being modified. The call returns the modified string, so you'd need to do this:

String modded = myDoubleString.replace(".",",");
System.out.println( modded );
Nishanthi Grashia
  • 9,787
  • 5
  • 42
  • 57
Chris Kessel
  • 5,331
  • 3
  • 34
  • 54
10

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

rink.attendant.6
  • 40,889
  • 58
  • 100
  • 149
vh.
  • 147
  • 1
  • 1
  • 6
  • Very good point! Your answer goes beyond my question, but solves the problem that I essentially had. I didn't know DecimalFormat, thanks! – CL23 Jul 22 '09 at 21:16
5

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

String newString = myDoubleString.replace(".", ",");
dfa
  • 111,277
  • 30
  • 187
  • 226
  • But you need not introduce `newString`, because although `String` objects are immutable, references to `String` objects can be changed (if they are not `final`): http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java – Raedwald Jan 02 '15 at 19:07
3

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 :)

Brian Beckett
  • 4,624
  • 6
  • 30
  • 52