Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将此字符串(包含字符串和int)转换为实际数字?(爪哇)_Java_String_Numbers_Double - Fatal编程技术网

Java 如何将此字符串(包含字符串和int)转换为实际数字?(爪哇)

Java 如何将此字符串(包含字符串和int)转换为实际数字?(爪哇),java,string,numbers,double,Java,String,Numbers,Double,我有一根绳子 String value = "The value of this product: 13,45 USD"; 我希望它是一个双人床,应该是这样的: double actualprice=13,45; 或者我应该使用float,double在这里没用?对不起,我不是专家 那么我如何将这个字符串转换成一个数字呢 哦,我差点忘了,我有一个代码,它指向“13,45”,但它仍然是一个字符串 String price = "The price is: 13.45"; Str

我有一根绳子

String value = "The value of this product: 13,45 USD";
我希望它是一个双人床,应该是这样的:

double actualprice=13,45;
或者我应该使用float,double在这里没用?对不起,我不是专家

那么我如何将这个字符串转换成一个数字呢

哦,我差点忘了,我有一个代码,它指向“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)+"");
}
}
String price=“价格为:13.45”;
字符串s=价格;

对于(int b=0;b此代码将起作用。如果未找到以不同方式格式化的字符串和编号,它将抛出
NumberFormatException

double actualprice = Double.parseDouble(
    value.replaceFirst("The value of this product: (\\d+),(\\d+) USD", "$1.$2"));

System.out.println(actualprice);
这可能会有帮助

    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();
            }
        }
    }

}

您可以尝试使用一些正则表达式,并将所有非数值替换为“”。然后您只需调用Double的解析方法:)如何将
13,45
存储在
Double
中?Double由于commaby的缘故,请不要使用浮点变量来存储金额。例如,用
BigDecimal
类来表示金额。对不起,它看起来不错,但我不明白。我真的很抱歉,我试着去理解,但是我不能:你能解释一下吗?因为我试图使用这段代码,我修改了一些部分,但它给了我一个错误。我的实际字符串是“$38.80 USD”,所以我尝试这样做:(“$:(\\d+),(\\d+)USD“,“$1.2”);但这给了我一个错误。