tags:

views:

353

answers:

5

How to implement VB's Val() function using Java programming language or is there any API that has the same method?

+6  A: 

You should use Integer.parseInt, Float.parseFloat, Double.parseDouble etc - or a NumberFormat instead, depending on whether you want to treat the input in a culture-sensitive manner or not.

EDIT: Note that these expect the string to contain the number and nothing else. If you want to be able to parse strings which might start with a number and then contain other bits, you'll need to clean the string up first, e.g. using a regular expression.

Jon Skeet
Those don't do the same thing that Val does. Unlike val, they expect clean strings.
Jonathan Allen
Thanks Grauenwolf - will edit.
Jon Skeet
basically I've "implemented" this answer, without the regular expression
dfa
A: 

If you want to convert a string to an integer use:

int x = Integer.parseInt(aString);
zPesk
+2  A: 

If my Google skills serve me, Val() converts a string to a number; is that correct?

If so, Integer.parseInt(myString) or Double.parseDouble(myString) are the closest Java equivalents. However, any invalid character causes them to treat the entire string as invalid; you can't parse, say, street numbers from an address with them.

Edit: Here is a method that is a closer equivalent:

public static double val(String str) {
    StringBuilder validStr = new StringBuilder();
    boolean seenDot = false;   // when this is true, dots are not allowed
    boolean seenDigit = false; // when this is true, signs are not allowed
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (c == '.' && !seenDot) {
            seenDot = true;
            validStr.append(c);
        } else if ((c == '-' || c == '+') && !seenDigit) {
            validStr.append(c);
        } else if (Character.isDigit(c)) {
            seenDigit = true;
            validStr.append(c);
        } else if (Character.isWhitespace(c)) {
            // just skip over whitespace
            continue;
        } else {
            // invalid character
            break;
        }
    }
    return Double.parseDouble(validStr.toString());
}

Test:

public static void main(String[] args) {
    System.out.println(val(" 1615 198th Street N.E."));
    System.out.println(val("2457"));
    System.out.println(val(" 2 45 7"));
    System.out.println(val("24 and 57"));
}

Output:

1615198.0
2457.0
2457.0
24.0

I can't vouch for its speed, but it is likely that Double.parseDouble is the most expensive part. I suppose it might be a little faster to do the double parsing in this function also, but I would have be certain that this is a bottleneck first. Otherwise, it's just not worth the trouble.

Michael Myers
It converts to Double. But I'm not sure how that maps in the Java type system.
Tomalak
A: 

try this:

Number Val(String value) {
    try {
        return NumberFormat.getNumberInstance().parse(value);
    } catch (ParseException e) {
        throw new IllegalArgumentException(value + " is not a number");
    }
}


Number a = Val("10");     // a instanceof Long 
Number b = Val("1.32");   // b instanceof Double
Number c = Val("0x100");  // c instanceof Long
dfa
Val will take the string "123 LakeView Dr." and return the nmber 123. Parse will not.
Jonathan Allen
you can simply ad a regular expression to strip non-numeric part.
dfa
+1  A: 
ValResult = Val(" 1615 198th Street N.E.") ' ValResult is set to 1615198
ValResult = Val("2457")                    ' ValResult is set to 2457.
ValResult = Val(" 2 45 7")                 ' ValResult is set to 2457.
ValResult = Val("24 and 57")               ' ValResult is set to 24.

any Java API can make the same behavior?

You'd probably want to use a regex to just remove any non-digits (possibly allowing . and - if you want non-integers and negative numbers... remember to escape the . though!)
Jon Skeet