在Java中将String转换为浮点数

dev*_*123 3 java google-app-engine android

我正在尝试将字符串pprice转换为浮点数.但是,对象的价格属性(浮动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);
}
Run Code Online (Sandbox Code Playgroud)

cla*_*esv 7

使用Double.parseDouble(string)或Float.parseFloat(string);


the*_*ber 5

你的问题在这里:

    String tokens[]=pprice.split(".");
Run Code Online (Sandbox Code Playgroud)

split的参数是正则表达式,"." 是一个匹配任何单个字符的正则表达式.要仅匹配点,您需要使用反斜杠将其转义,并且由于反斜杠也是特殊的,因此您需要将其加倍.

    String tokens[]=pprice.split("\\.");
Run Code Online (Sandbox Code Playgroud)

改变它,你的代码应该工作.

你可能最好使用其他答案中提到的解析方法之一.