"%" character in string

W

Wavequation

I am trying to remove the numerical portion of a string from a field holding
percentage values. I tried using the Val() function to do it, e.g.

Val("15.0%")

but the function returns a type mismatch error. What is the "%" character
doing to the string?
 
B

Banana

Interesting.

I tried this:

Val(151%) -> 151
Val(15.1) -> 15.1
Val(15.1%) -> Error

It's only the combination of both a decimal and % that causes problem,
not necessarily the '%' itself.

I also tried CDbl() and it errored out on the "15.1%"

I suppose one workaround would be to strip the % out.

Val(Replace("15.1%","%",""))

Note that Replace will not affect any strings that doesn't have % so you
can use it for both "15.1% and "15.1" and still get same result.
 
J

Jeff Boyce

"... holding percentage values ..." ... as what? Are they being stored as
text (i.e., characters), or as numeric values?

Regards

Jeff Boyce
Microsoft Office/Access MVP
 
V

vanderghast

It comes with an old convention that % is an acceptable suffix to designate
a short integer, so 15.1% is a contradiction. Try, in a module:

Public Sub SomFunction( )
Dim i As long
i = 15.1%
End Sub

and you will get a compile error. Same with:


Dim i As long
i = 33000%

here, because a short integer cannot represent 33000.



Vanderghast, Access MVP
 
B

Banana

Even inside a string? I'm pretty sure that type declaration character
don't work in a string and wouldn't be parsed as such as well...?

I suppose it'd make sense if it was just a "Val(15.1%)", but that wasn't
what I actually did. I actually forgot to add the delimiters in my reply
to OP. So, this:

Val("15.1%")

still fails with an error. This, without delimiting it as a string:

Val(15.1%)

fails with a different error, expecting an expression, probably because
Val() expects a string.
 
V

vanderghast

If you imagine for a moment that

Dim i As integer
i = 15.1%

is 'read' as a string, at some point, even if it represents code to be
executed, it is READ at some point, by the compiler, as STRING to be parsed,
then you can also imagine that

val("15.1%")


does somehow the same as the compiler, and reject the 'immediate constant
from a string' e-val-uation.


Vanderghast, Access MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top