Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hints for java.lang.String.replace problem? [duplicate]

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?

like image 313
CL23 Avatar asked Jul 22 '09 17:07

CL23


2 Answers

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);
like image 200
AlbertoPL Avatar answered Oct 21 '22 00:10

AlbertoPL


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 );
like image 45
Chris Kessel Avatar answered Oct 21 '22 01:10

Chris Kessel