How can I convert "1,000" (input obtained as a string) to an integer?
11 Answers
DecimalFormat df = new DecimalFormat("#,###");
int i = df.parse("1,000").intValue();
System.out.println(i);
1 Comment
Sahil Jain
A generic approach colud be like this. Integer.parseInt("1,000".replaceAll("[^\\d.]", ""))
Integer i = Integer.valueOf("1,000".replaceAll(",", ""));
2 Comments
Patrick Ferreira
better : System.out.println(Integer.parseInt("1,000".replaceAll("\\D+", "")));
Jules
@Peter Lawrey: It's programming with a positive attitude ;)
String stringValue = "1,000";
String cleanedStringValue = stringValue.replace(',','');
int intValue = Integer.parseInt(cleanedStringValue);
2 Comments
bstack
Becuase for some reason it was not rendering the code properly when the comments were included! Pardon me but Im new to all of this stackoverflow stuff!
Harry Joy
Look at 3rd revision here: stackoverflow.com/posts/5470551/revisions which is made by me. It shows comment and code both well.
1 Comment
Heiko Rupp
Does not work. See documentation "The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value."
I'd take a look at this class: http://download.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html
Comments
Just replace all comma with empty string and then use convert.ToInt32();
string str = "1,000";
int num = Integer.parseInt(str.replace(",",""));
2 Comments
user673218
I need to perform the conversion in java!
Sachin Shanbhag
@user673218 - This is available in java too ;)
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.
1 Comment
greg-449
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.