【问题标题】:How to transform this String (contains string and int) to an actual number? (Java) [duplicate]如何将此字符串(包含字符串和 int)转换为实际数字? (Java)[重复]
【发布时间】:2015-07-13 23:10:15
【问题描述】:

我有一个字符串。

String value = "The value of this product: 13,45 USD";

我希望它是一个双倍,应该是这样的:

double actualprice=13,45;

或者我应该使用浮点数,双精度在这里没用?抱歉,我不是专家。

那么我怎样才能把这个字符串转换成一个数字呢?

哦,我差点忘记了,我有一个代码,它是“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)+"");
}
}

【问题讨论】:

  • 你云尝试使用一些正则表达式并将所有非数字值替换为“”。然后你只需要调用 Double 的 parse 方法 :)
  • 你的店铺13,45怎么能在double中?
  • 双因为逗号
  • 顺便说一下,不要使用浮点变量来存储金额。例如,要表示金额,请使用 BigDecimal 类。

标签: java string numbers double


【解决方案1】:

此代码将起作用。如果未找到以不同方式和数字格式化的字符串,它将抛出NumberFormatException

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

System.out.println(actualprice);

【讨论】:

  • 对不起,看起来不错,但我听不懂。我真的很抱歉,我试图理解,但我不能:D 你能解释一下吗?因为我尝试使用此代码,所以我修改了一些部分,但它给了我一个错误。对我来说实际的字符串是 "$38.80 USD" 所以我试着这样做: ("$: (\\d+),(\\d+) USD", "$1.$2"));但它给了我一个错误。
【解决方案2】:

这可能会有所帮助。

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

}

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 2015-05-25
    • 2016-07-07
    • 2020-07-27
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多