Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert VB's Val to Java?

Tags:

java

vb6

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


2 Answers

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.

like image 89
Jon Skeet Avatar answered Jul 02 '26 14:07

Jon Skeet


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.

like image 38
Michael Myers Avatar answered Jul 02 '26 13:07

Michael Myers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!