1

I have a text (String) an I need to get only digits from it, i mean if i have the text:

"I'm 53.2 km away", i want to get the "53.2" (not 532 or 53 or 2)

I tried the solution in Extract digits from a string in Java. it returns me "532".

Anyone have an idea for it?

Thanx

Community
  • 1
  • 1
kande
  • 559
  • 1
  • 10
  • 28

6 Answers6

9

You can directly use a Scanner which has a nextDouble() and hasNextDouble() methods as below:

        Scanner st = new Scanner("I'm 53.2 km away");
        while (!st.hasNextDouble())
        {
            st.next();
        }
        double value = st.nextDouble();
        System.out.println(value);

Output: 53.2

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
3

Here is good regex site with tester:

http://gskinner.com/RegExr/

this works fine \d+\.?\d+

dantuch
  • 9,123
  • 6
  • 45
  • 68
3
import java.util.regex.*;

class ExtractNumber
{
    public static void main(String[] args)
    {
        String str = "I'm 53.2 km away";
        String[] s = str.split(" ");
        Pattern p = Pattern.compile("(\\d)+\\.(\\d)+");
        double d;
        for(int i = 0; i< s.length; i++)
        {
            Matcher m = p.matcher(s[i]);
            if(m.find())
                d = Double.parseDouble(m.group());
        }
        System.out.println(d);
    }
}
Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
  • 1
    Note that this will also match as whole _53.2km_, i.e. it won't strip the `km`. The example does use a space, though so this is only a nit. – pb2q Jun 10 '12 at 18:20
  • @pb2q: replaced `s[i]` with `m.group()` this should solve the problem you pointed out. – Surender Thakran Jun 10 '12 at 18:23
1

The best and simple way is to use a regex expression and the replaceAll string method. E.g

String a = "2.56 Kms";

String b = a.replaceAll("\\^[0-9]+(\\.[0-9]{1,4})?$","");

Double c = Double.valueOf(b);

System.out.println(c);
Amimo Benja
  • 505
  • 5
  • 8
0

If you know for sure your numbers are "words" (space separated) and don't want to use RegExs, you can just parse them...

String myString = "I'm 53.2 km away";
List<Double> doubles = new ArrayList<Double>();
for (String s : myString.split(" ")) {
    try {
        doubles.add(Double.valueOf(s));
    } catch (NumberFormatException e) {
    }
}
nbarraille
  • 9,926
  • 14
  • 65
  • 92
  • 4
    and create lots of useless Exception objects? – dantuch Jun 10 '12 at 18:19
  • @dantuch They're not useless: they're signalling that the `String` could not be parsed. – Jeffrey Jun 10 '12 at 18:23
  • 2
    @Jeffrey No! They shouldn't be created in first place. You know what "Exception driven development" stands for? Just don't use exceptions in situations that are NOT exceptional. Parsing `I'm` to double ending in fail isn't exception at all. – dantuch Jun 10 '12 at 18:30
  • @dantuch But the exceptions are still not useless, they are performing a task. They are, however, unnecessary. – Jeffrey Jun 10 '12 at 18:34
0

I have just made a method getDoubleFromString. I think it isn't best solution but it works good!

public static double getDoubleFromString(String source) {
        if (TextUtils.isEmpty(source)) {
            return 0;
        }

        String number = "0";
        int length = source.length();

        boolean cutNumber = false;
        for (int i = 0; i < length; i++) {
            char c = source.charAt(i);
            if (cutNumber) {
                if (Character.isDigit(c) || c == '.' || c == ',') {
                    c = (c == ',' ? '.' : c);
                    number += c;
                } else {
                    cutNumber = false;
                    break;
                }
            } else {
                if (Character.isDigit(c)) {
                    cutNumber = true;
                    number += c;
                }
            }
        }
        return Double.parseDouble(number);
    }