Convert VB Val to Java?

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

+3
source share
6 answers

You must use the Integer.parseInt, Float.parseFloat, Double.parseDoubleetc. - or NumberFormatinstead, depending on whether you want to handle the input in a culture-sensitive way or not.

EDIT: Note that they expect the string to contain a number and nothing else. If you want to analyze strings that can start with a number and then contain other bits, you must first clear the string, for example. using regex.

+7
source

Google , Val() ; ?

, Integer.parseInt(myString) Double.parseDouble(myString) Java. ; , , .

: :

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

:

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

:

1615198.0
2457.0
2457.0
24.0

, , , Double.parseDouble - . , , , , . .

+4

:

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
0
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.

Java API ?

0

:

int x = Integer.parseInt(aString);
-2

Source: https://habr.com/ru/post/1708177/


All Articles