I’m trying to convert the string pprice to a floating point number. However, the object’s price attribute(floating pt type) is setting as 0.00.. Can someone pls tell me what’s wrong?
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);
}
Your problem is here:
The argument to split is a regular expression, and “.” 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.
Change that and your code should work.
You’d probably be better off using one of the parse methods mentioned in the other answers.