3

i'm parsing out Long values from given String-s.

Long.valueOf() and Long.parseLong() wouldn't work - because such a String str is in the format 1,234,567 and can be surrounded by spaces.

I can work this by processing the String to get it to bare digits-- then parsing the value out. so - it would be something like

str.trim(); 
String tempArray [] = str.split(","); 
str = ""; 
for (String s:tempArray)
    str+=s; 

however, there must be a better way of doing this. What is it?

user4402742
  • 91
  • 1
  • 11

3 Answers3

6

You can use NumberFormat here, with appropriate Locale. US locale would suffice here. You've to take care of whitespaces though.

String str = "1,234,567";
NumberFormat format = NumberFormat.getInstance(Locale.US);
System.out.println(format.parse(str.replace(" ", "")));

You can even use DecimalFormat which is slightly more powerful. You can add any grouping or decimal separator:

DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator(',');
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);

System.out.println(decimalFormat.parse(str.replace(" ", "")));
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

Of course it is possible :)

String newStr = str.replaceAll(",","");

For removing even spaces :

String newStr = str.replaceAll(",","").replaceAll(" ","");

And you can pass it to Long immediately

Long myLong = Long.valueOf(str.replaceAll(",","").replaceAll(" ",""));
libik
  • 22,239
  • 9
  • 44
  • 87
4

The replaceAll method can remove your commas and trim removes white space:

Long.parseLong(str.trim().replaceAll(",", ""))
Neil Masson
  • 2,609
  • 1
  • 15
  • 23