[英]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. 如何将字符串值转换为整数并将转换后的值乘以整数,以便得到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;
Use Interger.parseInt(String) or Float.parseFloat(String) 使用Interger.parseInt(String)或Float.parseFloat(String)
refer API documentation 请参阅API文档
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html
使用Integer.parseInt()方法转换为整数。
尝试这个
int n = NumberFormat.getIntegerInstance().parse(str).intValue();
If the String only contains numeric values you can use 如果字符串仅包含数字值,则可以使用
Integer.parseInt(string); 的Integer.parseInt(字符串); or Float.parseFloat(string);
或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. 对于您的示例,“ USD”部分将导致此操作失败,因此您很有可能必须先将其剥离。
eg string.split(" "); 例如string.split(“”);
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. 如果您尝试直接在str上
parseFloat
,则将得到“ NumberFormatException”,因为它包含字符串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. 编辑 :尝试使用
DecimalFormat
新添加的代码,并根据需要使用resultString。
you will get a NumberFormatException
as "60.00 USD"
is not a float. 您会收到
NumberFormatException
因为"60.00 USD"
不是浮点数。 To make it right you have to remove the currency. 为了使其正确,您必须删除货币。 There can be many ways to remove the usd.
有很多方法可以删除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"
现在,您有了一个A字符串,其值为
"60.00"
so you can do this now 所以你现在就可以做
float f = Float.parseFloat(s);
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.