我有一个字符串。
String value = "The value of this product: 13,45 USD";
我希望它是双重的,应该是:
double actualprice=13,45;
或者我应该使用float,double在这里没用吗?对不起,我不是专家。
那么如何将此字符串转换为数字呢?
哦,我差点忘了,我有一个代码,这使得它成为了#134;" 13,45"但它仍然是一个字符串。 String price = "The price is: 13.45";
String s = price;
for(int b=0;b<s.length();b++){
if(s.charAt(b)=='.') {
System.out.print(",");
}
if(Character.isDigit(s.charAt(b))) {
System.out.print(s.charAt(b)+"");
}
}
答案 0 :(得分:0)
此代码可以使用。如果找不到以不同方式和数字格式化的字符串,它将抛出NumberFormatException
。
double actualprice = Double.parseDouble(
value.replaceFirst("The value of this product: (\\d+),(\\d+) USD", "$1.$2"));
System.out.println(actualprice);
答案 1 :(得分:0)
这可能会有所帮助。
public class RegexTest1 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+,\\d+");
Matcher match = p.matcher("The value of this product: 13,45 USD");
Double d ;
while (match.find()) {
System.out.println(match.group());
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
try {
d = (Double)df.parse(match.group());
System.out.println(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}