[java] How to replace comma (,) with a dot (.) using java

I am having a String str = 12,12 I want to replace the ,(comma) with .(Dot) for decimal number calculation, Currently i am trying this :

 if( str.indexOf(",") != -1 )
 {
     str.replaceAll(",","\\.");
 }

please help

This question is related to java string

The answer is


For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

Just use replace instead of replaceAll (which expects regex):

str = str.replace(",", ".");

or

str = str.replace(',', '.');

(replace takes as input either char or CharSequence, which is an interface implemented by String)

Also note that you should reassign the result


if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }

or even better

str = str.replace(',', '.');

Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:

str = str.replaceAll(",","."); // or "\\.", it doesn't matter...

in the java src you can add a new tool like this:

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");
}

Use this:

String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12

hope help you.


str = str.replace(',', '.')

should do the trick.


Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.