28

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

oliholz
  • 7,447
  • 2
  • 43
  • 82
alpesh
  • 291
  • 1
  • 3
  • 3

9 Answers9

53

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...
MByD
  • 135,866
  • 28
  • 264
  • 277
19

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
16
str = str.replace(',', '.')

should do the trick.

davek
  • 22,499
  • 9
  • 75
  • 95
2
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }

or even better

str = str.replace(',', '.');
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
2

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.

lonerook
  • 99
  • 3
2

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

str.replaceAll(",", ".");
Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
1

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

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");
}
josliber
  • 43,891
  • 12
  • 98
  • 133
Merlook
  • 11
  • 1
1

Use this:

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

hope help you.

Yugerten
  • 878
  • 1
  • 11
  • 30
0

If you want to change it in general because you are from Europe and want to use dots instead of commas for reading an input with a scaner you can do it like this:

Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
System.out.println(sc.locale().getDisplayCountry());

Double accepted with comma instead of dot

maxmitz
  • 258
  • 1
  • 4
  • 17