[英]Convert a String to floating point number in java
I'm trying to convert the string pprice to a floating point number. 我正在尝试将字符串pprice转换为浮点数。 However, the object's price attribute(floating pt type) is setting as 0.00.. Can someone pls tell me what's wrong?
但是,对象的价格属性(浮动pt类型)设置为0.00 ..有人可以告诉我有什么问题吗?
String pprice="60.0"
String tokens[]=pprice.split(".");
if(tokens.length>=2)
{
int a=Integer.parseInt(tokens[0]);
int b=Integer.parseInt(tokens[1]);
float a1=(float)a;
float b1=(float)b;
Float price=a1+(b1/100);
prod.setProductPrice(price);
}
else if(tokens.length==1)
{
int a=Integer.parseInt(tokens[0]);
float a1=(float)a;
prod.setProductPrice(a1);
}
使用Double.parseDouble(string)或Float.parseFloat(string);
Your problem is here: 你的问题在这里:
String tokens[]=pprice.split(".");
The argument to split is a regular expression, and "." split的参数是正则表达式,“。” is a regular expression that matches any single character .
是一个匹配任何单个字符的正则表达式。 To match only the dot, you need to escape it with a backslash, and since the backslash is also special, you need to double it.
要仅匹配点,您需要使用反斜杠将其转义,并且由于反斜杠也是特殊的,因此您需要将其加倍。
String tokens[]=pprice.split("\\.");
Change that and your code should work. 改变它,你的代码应该工作。
You'd probably be better off using one of the parse methods mentioned in the other answers. 你可能最好使用其他答案中提到的解析方法之一。
Let's try float.parseFloat("60.0");
我们来试试
float.parseFloat("60.0");
or Double.parseDouble("60.0");
或
Double.parseDouble("60.0");
Why don't you use something like: 你为什么不用这样的东西:
float price = Float.valueOf(pprice.trim());
(equivalent to Float.parseFloat(string)) (相当于Float.parseFloat(string))
float urfloat=Float.parseFloat(String string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.