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 n开发者_如何学Goumber calculation,
Currently i am trying this :
if( str.indexOf(",") != -1 )
{
str.replaceAll(",","\\.");
}
please help
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...
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
str = str.replace(',', '.')
should do the trick.
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
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.
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
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.
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
精彩评论