Search code examples
javastringnumbersstring-parsing

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?


Solution

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