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
  • 46,419
  • 33
  • 155
  • 245
AlbertoPL
  • 11,479
  • 5
  • 49
  • 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 );
ngrashia
  • 9,869
  • 5
  • 43
  • 58
Chris Kessel
  • 5,583
  • 4
  • 36
  • 55
10

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

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
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
  • 114,442
  • 31
  • 189
  • 228
  • 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,742
  • 6
  • 33
  • 52