user673218
user673218

Reputation: 411

Integer value of strings

How can I convert "1,000" (input obtained as a string) to an integer?

Upvotes: 1

Views: 6558

Answers (11)

Rémi Surget
Rémi Surget

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

sushil bharwani
sushil bharwani

Reputation: 30187

with a comma (,) in the the string you probably cannot do it.

Upvotes: 0

bstack
bstack

Reputation: 2528

String stringValue = "1,000";

String cleanedStringValue = stringValue.replace(',','');

int intValue = Integer.parseInt(cleanedStringValue);

Upvotes: 2

Sachin Shanbhag
Sachin Shanbhag

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

Ciaran McHale
Ciaran McHale

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

topless
topless

Reputation: 8221

Integer.parseInt("1000");

Prefer avoiding "magic numbers"

String num = "1000";
Integer.parseInt(num);

Upvotes: 0

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

String str ="1000";

Try this

 int i = Integer.valueOf("1,000".replaceAll(",", ""));

Upvotes: 0

MarcoS
MarcoS

Reputation: 13564

Integer i = Integer.valueOf("1,000".replaceAll(",", ""));

Upvotes: 3

Peeter
Peeter

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

Nishan
Nishan

Reputation: 2871

    DecimalFormat df = new DecimalFormat("#,###");
    int i = df.parse("1,000").intValue();
    System.out.println(i);

Upvotes: 7

Related Questions