Reputation: 411
How can I convert "1,000" (input obtained as a string) to an integer?
Upvotes: 1
Views: 6558
Reputation: 1
Always prefer to use Long.ValueOf
instead of new Long. Indeed, the new Long always result in a new object whereas Long.ValueOf
allows to cache the values by the compiler. Thanks to the cache, you code will be faster to execute.
Upvotes: 0
Reputation: 30187
with a comma (,
) in the the string you probably cannot do it.
Upvotes: 0
Reputation: 2528
String stringValue = "1,000";
String cleanedStringValue = stringValue.replace(',','');
int intValue = Integer.parseInt(cleanedStringValue);
Upvotes: 2
Reputation: 55489
Just replace all comma with empty string and then use convert.ToInt32();
string str = "1,000";
int num = Integer.parseInt(str.replace(",",""));
Upvotes: 0
Reputation: 2234
Use code like the following.
String str = "1000";
int result;
try {
result = Integer.parseInt(str);
} catch(NumberFormatException ex) {
System.err.println("That was not an integer");
}
Upvotes: 0
Reputation: 8221
Integer.parseInt("1000");
Prefer avoiding "magic numbers"
String num = "1000";
Integer.parseInt(num);
Upvotes: 0
Reputation: 46395
String str ="1000";
Try this
int i = Integer.valueOf("1,000".replaceAll(",", ""));
Upvotes: 0
Reputation: 9382
I'd take a look at this class: http://download.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html
Upvotes: 1
Reputation: 2871
DecimalFormat df = new DecimalFormat("#,###");
int i = df.parse("1,000").intValue();
System.out.println(i);
Upvotes: 7