chuck finley
chuck finley

Reputation: 459

sort doubles stored as strings ?

Hi is there any way to parse strings into numbers? And is there any way to check if a string is a number or not without breaking the program ? I am thinking about using a try and catch would this be a good idea ?

Upvotes: 2

Views: 291

Answers (5)

Lav
Lav

Reputation: 96

You can use regex to find if the strings is double or not

if(num1.matches(("((-|\\+)?[0-9]+(\\.[0-9]+)?)+"))){
    isDoubleVal =true;                  
}else{
    isDoubleVal = false;
}

Hope it helps you.

Regards, Lav

Upvotes: 0

azernik
azernik

Reputation: 1228

I'm assuming you want to sort using one of the assorted built-in sort methods. In that case, you'll need to create a custom Comparator<T>, implementing compare() and equals() that attempts to parse the strings as Double, and on catching an exception, implements some sane default behavior. Make sure to catch the exception within your methods - you should only run into problems if you let the exceptions get out into the Java API code.

As a quick example to get you going:

class DoubleStringComparator implements Comparator<String> {

    public int compare(String o1, String o2) {
        try {
            double d1 = Double.parse(o1);
            double d2 = Double.parse(d2);
            if d1 > d2 {
                return 1;
            } else if d1 < d2 {
                return -1;
            else {
                return 0;
            }
        } catch (NumberFormatException e) {
            // whatever ordering you want to impose when one string is not a double
        }
    }

    // some definition of equals() - whatever makes sense for your application

}

Then, when you want to do the sorting:

Collections.sort(someListOfString, new DoubleStringComparator());

Upvotes: 1

Manuel Selva
Manuel Selva

Reputation: 19050

Yes. Double.valueOf(String s) will throw a NumberFormatException if your string can't be parsed to a Double and return the parsed Double otherwise.

Upvotes: 3

stivlo
stivlo

Reputation: 85476

Take a look at parseDouble

http://download.oracle.com/javase/6/docs/api/java/lang/Double.html#parseDouble%28java.lang.String%29

and yes you can catch NumberFormatException to determine when the number wasn't valid.

Upvotes: 0

Oliver
Oliver

Reputation: 11597

There's no way to check if a string is parseable or not without trying to parse the string (as any check would have to start trying to interpret the string as a number to do that...). For a half-way check, I guess you could use Regex to check if the string has only digits and periods. You'll have to use a try... catch block aswell, though.

As to how to parse a string into a double, try this:

double dd;
try {
    dd = Double.parseDouble(string);
}
catch (NumberFormatException e) {
    System.out.println("couldnt not parse the string!");
}

Upvotes: 4

Related Questions