user4402742
user4402742

Reputation: 91

Parsing a number from a string with thousands seperators

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?

Upvotes: 3

Views: 1760

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213263

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(" ", "")));

Upvotes: 6

Neil Masson
Neil Masson

Reputation: 2689

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

Long.parseLong(str.trim().replaceAll(",", ""))

Upvotes: 4

libik
libik

Reputation: 23029

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(" ",""));

Upvotes: 4

Related Questions