First, just so we know where we are starting, here's the VB help file info on Val:
"The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument"
But it isn't complete - as we shall see
So, in your example, when Val hits the % symbol it should discard it, and stop parsing the string (it sure as heck doesn't go "ah, we're dealing with a percentage"; it isn't that smart).
Now, as you have observed, it correctly seems to do this when the value is "30.00%", but not when "0.00%". Nor will it work with values such as "30.01%", "9.8%".
In all of these non-working examples if you change the % to, say, * they all miraculously work properly (as per the help file documentation). On the other hand, they won't if you replace the % with &
So what is going on? Well, the problem is that Val is interacting with a low-level VB expression evaluator. And we need to remind ourselves that VB, mostly for legacy reasons, supports postfix symbols to define variable types, eg $ = string, # = double, % = integer, & = long.
Let's consider one of the non-working examples, such as "30.01%". What happens is that character by character Val starts building the numerical equivalent of the string using the low-level expression evaluator. It goes something like this (and this is a gross simplification, but should get the idea across):
3 - OK, I've got 3 - 3
0 - Ok, got a 0 - 30
. - got decimal seperator, let's wait and see whether we've got anything after it - 30
0 - no, nothing significant yet - 30
1 - ah, yes got first digit. Definitely a floating point number - 30.01
% - OK, now I'm being told that the number I'm parsing is an integer. Wait a minute, what I've actually got so far is a floating point number! That's a type mismatch!
In other words, the missing part of the Val documentation is that it will pick up and try to apply postfix type definition characters (and terminate parsing at that point)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.