I'm parsing a file that has integer values using commas to separate thousands.
String s = "1,503"
Integer i = new Integer(s)
does not work, throws a parse exception. Is there an easy way to parse this?
Thanks
A slightly more groovy method might be;
int a = java.text.NumberFormat.instance.parse( '1,234' )
But this will use the default locale
Use NumberFormat
instead. For example, in Java:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String args[]) throws ParseException {
NumberFormat format = NumberFormat.getIntegerInstance(Locale.US);
Long parsed = (Long) format.parse("1,234");
System.out.println(parsed);
}
}
(You can then get the integer value from the Long
, of course.)
I've explicitly specified Locale.US
to guarantee that comma is used as the thousands separator; you may want to use a different locale if the input can vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With