How can I convert a string
(1,234)
into a number
(1234)
using java?
Use DecimalFormat
DecimalFormat format = new DecimalFormat ("#,###");
Number aNumber = format.parse("1,234");
System.out.println(aNumber.intValue());
you can use NumberFormat
for that
String number = "1,234";
NumberFormat numberFormat = NumberFormat.getInstance();
int i = numberFormat.parse(number).intValue();
String value = "1,234";
System.out.println(Integer.parseInt(value.replaceAll(",", "")));
String str = new String("1,234");
String str1=str.replace(",", "");
Integer.parseInt(str1);
try with the above code
output 1234
String is immutable, so when you do replaceAll, you need to reassign object to string reference,
String str = new String("1,234");
str = str.replaceAll(",", "");
System.out.println(Integer.parseInt(str));
This works fine when tested.
If speed was a major concern you may find something like this quite fast. It beat all comers in this post.
int value(String s) {
// Start at zero so first * 10 has no effect.
int v = 0;
// Work from the end of the string backwards.
for ( int i = s.length() - 1; i >= 0; i-- ) {
char c = s.charAt(i);
// Ignore non-digits.
if ( Character.isDigit(c)) {
// Mul curent by 10 and add digit value.
v = (v * 10) + (c - '0');
}
}
return v;
}