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

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

3

Here is good regex site with tester:

http://gskinner.com/RegExr/

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

Comments

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

2 Comments

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: replaced s[i] with m.group() this should solve the problem you pointed out.
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);

Comments

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) {
    }
}

4 Comments

and create lots of useless Exception objects?
@dantuch They're not useless: they're signalling that the String could not be parsed.
@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 But the exceptions are still not useless, they are performing a task. They are, however, unnecessary.
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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.