Question:
How can I convert String of numbers with commas to Long?
Answer:
Remove commas from the string with str.replaceAll(",", "").
or
Use the NumberFormat class.
or
Use the NumberFormat class.
Code:
import java.text.NumberFormat; import java.util.Locale; import java.text.ParseException; public class NumbersWithCommas { public static void main(String[] args) { String str = "1,234,567,890"; // remove all commas in the string long l1 = Long.valueOf(str.replaceAll(",", "").toString()); System.out.println("l1: " + l1); NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = 0; try { number = format.parse(str); } catch (ParseException e) { e.printStackTrace(); } long l2 = number.longValue(); System.out.println("l1: " + l1); } }
Output:
$ java NumbersWithCommas l1: 1234567890 l1: 1234567890