Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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

like image 973
alpesh Avatar asked May 18 '11 11:05

alpesh


People also ask

How do you replace a comma with a dot?

Use the replace() method to replace all commas with dots, e.g. const replaced = str1. replace(/,/g, '. '); . The replace method will return a new string with all commas replaced by dots.

How do you remove the dot and comma from a string in Java?

Remove Punctuation From String Using the replaceAll() Method in Java. We can use a regex pattern in the replaceAll() method with the pattern as \\p{Punct} to remove all the punctuation from the string and get a string punctuation free. The regex pattern is \\p{Punct} , which means all the punctuation symbols.

How do you replace text in Java?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.


2 Answers

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... 
like image 73
MByD Avatar answered Sep 28 '22 02:09

MByD


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

like image 24
Bozho Avatar answered Sep 28 '22 02:09

Bozho