I have a String value like "1.22%". I want to convert this to double value. Douboe.parseDouble throws numberFormatException.
String s = "1.22%";
double iRate;
iRate = Double.parseDouble(s);
One-liner using DecimalFormat :
double d = new DecimalFormat("0.0#%").parse("1.22%").doubleValue();
// d = 0.0122
You want to use a method similar to the one below:
public static double ConvertPercentageStringToDouble(this string value)
{
return double.Parse(value.Replace("%","")) / 100;
}
Assuming you have standard format. You can try
String s = "1.22%";
s = s.replaceAll("%","");
double iRate= Double.parseDouble(s);
The better way to do this is using DecimalFormatSymbols , which can help you to define what is simbols and what is really numbers to transform into Double.
See the example below:
String s = "1.22%";
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
symbols.setPercent('%');
df.setDecimalFormatSymbols(symbols);
Number parse = df.parse(s);
Double myDouble = parse.doubleValue();
System.out.println(myDouble);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.