Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a double out of a string

Tags:

java

i have a string containing the following: "Did It Your Way, 11.95 The History of Scotland, 14.50, Learn Calculus in One Day, 29.95" is there any way to get the doubles from this string?

like image 953
Edward Avatar asked Jul 18 '11 14:07

Edward


3 Answers

This finds doubles, whole numbers (with and without a decimal point), and fractions (a leading decimal point):

public static void main(String[] args)
{
    String str = "This is whole 5, and that is double 11.95, now a fraction .25 and finally another whole 3. with a trailing dot!";
    Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(str);
    while (m.find())
    {
        double d = Double.parseDouble(m.group(1));
        System.out.println(d);
    }
}

Output:

5.0
11.95
0.25
3.0
like image 61
Bohemian Avatar answered Oct 26 '22 13:10

Bohemian


Use regular expressions to extract doubles, then Double.parseDouble() to parse:

Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
Matcher m = p.matcher(str);
while(m.find()) {
    double d = Double.parseDouble(m.group(1));
    System.out.println(d);
}
like image 34
AlexR Avatar answered Oct 26 '22 11:10

AlexR


Java provides Scanner which allows you to scan a String (or any input stream) and parse primitive types and string tokens using regular expressions.

It would likely be preferrable to use this rather than writing your own regex, purely for maintenance reasons.

Scanner sc = new Scanner(yourString);
double price1 = sc.nextDouble(), 
       price2 = sc.nextDouble(), 
       price3 = sc.nextDouble();
like image 36
Ian Bishop Avatar answered Oct 26 '22 12:10

Ian Bishop