How to implement VB's Val() function using Java programming language or is there any API that has the same method?
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.
If you want to convert a string to an integer use:
int x = Integer.parseInt(aString);
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.
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
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?