2

I have a string.

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

I want it to be a double which should be like:

double actualprice=13,45;

Or should i use float, double is useless here? Sorry, i am not an expert.

So how can i transform this string to a number?

oh and i almost forgot, i've got a code, which makes it to "13,45" but it's still a String.

    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)+"");
}
}
maxgraham
  • 23
  • 3

2 Answers2

0

This code will work. It will throw a NumberFormatException if the string formatted in different manner and number was not found.

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

System.out.println(actualprice);
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • excuse me, it looks good, but i can't understand. I am really sorry, i tried to understand but i couldn't :D Can you explain please? Because i tried to use this code, i modified some part but it gives me an error. The actual string for me is "$38.80 USD" so i tried to do like this: ("$: (\\d+),(\\d+) USD", "$1.$2")); but it gives me an error. – maxgraham May 04 '15 at 16:35
0

This may be helpful.

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

}
Rahul
  • 3,479
  • 3
  • 16
  • 28