user2042881
user2042881

Reputation: 125

convert string value in to integer

How to convert string value into integer and multiply the converted value to integer so that I can get the result as 300.00. See example below -

int value = 5;
String  str = "60.00 Cur";

If I code like these then I am getting error -

Float f = new Float(app.price.get(position));           
double d = f.doubleValue();                 
int i = (int)d;

Upvotes: 0

Views: 541

Answers (7)

midhunhk
midhunhk

Reputation: 5554

Can you try the following code and see if this is what you want? The final answer will be present in the variable "result".

String str = "60.00 USD";
int value = 5;
String dollarValue = str.split(" ")[0];
Float price = Float.parseFloat(dollarValue );
Float result = price * value;

DecimalFormat df = new DecimalFormat("#.##");
df.setMinimumFractionDigits(2);
String resultString = df.format(result);

You will get a "NumberFormatException" if you try to parseFloat on str directly as it contains the string USD. Here we will split that and take the first part.

Edit: Try the newly added code with DecimalFormat and use the resultString for your purpose.

Upvotes: 0

SilentCoder
SilentCoder

Reputation: 2000

Use,

 Integer.parseInt("value you want to parse as int")

likewise you can use,

Double.parseDouble("value");

This is answer for your Question

int result = Integer.parseInt("150.00 USD")* Integer.parseInt("5");

Upvotes: 0

stinepike
stinepike

Reputation: 54672

you will get a NumberFormatException as "60.00 USD" is not a float. To make it right you have to remove the currency. There can be many ways to remove the usd. For example

String s = "60.00 USD";
s = s.replace(" USD" , "");

or if the currency is not fixed

s = s.split(" ")[0];

Now you have A string s whose value is "60.00"

so you can do this now

float f = Float.parseFloat(s);

Upvotes: 0

Andrew Wilkinson
Andrew Wilkinson

Reputation: 248

If the String only contains numeric values you can use

Integer.parseInt(string); or Float.parseFloat(string);

As for your example, the "USD" part will cause this to fail, so you'll probbaly have to strip this part out first.

e.g. string.split(" ");

Upvotes: 0

Sid
Sid

Reputation: 371

Use Integer.parseInt() method to convert to integer.

Upvotes: 2

Abhijith Nagarajan
Abhijith Nagarajan

Reputation: 4030

Use Interger.parseInt(String) or Float.parseFloat(String)

refer API documentation

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

int n = NumberFormat.getIntegerInstance().parse(str).intValue();

Upvotes: 1

Related Questions