2013-10-07 69 views
0

如何將字符串值轉換爲整數並將轉換後的值乘以整數以便我可以得到結果爲300.00。見下面的例子 -將字符串值轉換爲整數

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

如果我的代碼這樣的話,我我得到的錯誤 -

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

能否請您澄清這個問題嗎? – midhunhk

+0

請參閱http://stackoverflow.com/questions/how-to-ask – saikosen

回答

0

你可以試試下面的代碼,看看這是你想要的嗎?最終答案將出現在變量「結果」中。

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); 

你會得到一個「NumberFormatException的」如果你試圖parseFloat在海峽直接,因爲它包含字符串美元。在這裏,我們將分解並採取第一部分。

編輯:嘗試新添加的代碼DecimalFormat並使用resultString爲您的目的。

+0

我想要得到的結果爲300.00它得到300.0 – user2042881

+0

我已經使用DecimalFormat格式更新了答案。你可以試試這個代碼嗎? – midhunhk

1

試試這個

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

使用Integer.parseInt()方法將其轉換爲整數。

0

如果字符串僅包含數字值,你可以使用

的Integer.parseInt(串);或者 Float.parseFloat(string);

至於你的例子,「美元」部分將導致這個失敗,所以你會probbaly不得不剝奪這部分首先。

例如string.split(「」);

0

您將獲得NumberFormatException作爲"60.00 USD"不是浮動。爲了使它正確,你必須刪除貨幣。可以有很多方法來移除usd。例如

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

,或者如果貨幣不固定

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

現在你有一個字符串s,其值是"60.00"

這樣你就可以做到這一點,現在

float f = Float.parseFloat(s); 
0

使用,

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

同樣可以使用,

Double.parseDouble("value"); 

這是回答你的問題

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