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?

2
  • 5
    This has tripped up soooo many Java newbies over the years. Commented Jul 22, 2009 at 17:32
  • 2
    I have re-read the docs of replace and it clearly starts with "Returns a new string ..." ;-) Commented Jul 22, 2009 at 17:36

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

As usual the problem sits in front of the computer ;-) Thx
The reason it returns a new string is that Strings are immutable in Java.
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 );

Comments

10

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

1 Comment

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

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

String newString = myDoubleString.replace(".", ",");

1 Comment

But you need not introduce newString, because although String objects are immutable, references to String objects can be changed (if they are not final): stackoverflow.com/questions/1552301/…
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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.