Confused about str()

  • Thread starter Thread starter Ferris
  • Start date Start date
F

Ferris

I'm curious to know as to why if:

x = 1

str(x) = "1" equates to FALSE.

I've tried x as Long, Integer, etc. Does anyone know why?

Thanks.
 
The str function leaves a leading space for the sign as per its description

"Remarks

When numbers are converted to strings, a leading space is always reserved
for the sign of number. If number is positive, the returned string contains a
leading space and the plus sign is implied."

If you don't want the leading space use CStr function...

Sub test()
Dim x As Integer

x = 1
MsgBox str(x) = " 1" 'equates to true
End Sub

Sub test()
Dim x As Integer

x = 1
MsgBox Cstr(x) = "1" 'equates to true
End Sub
 
The str function leaves a leading space for the sign as per its
description

"Remarks

When numbers are converted to strings, a leading space is always reserved
for the sign of number. If number is positive, the returned string
contains a
leading space and the plus sign is implied."

If you don't want the leading space use CStr function...

You can also use the Format function (although, since we know we want a
String value back, I would use Format$ of the function instead).

x = 1

Format$(x) = "1" --- evaluates to True

This is documented in the Remarks section of the help file for the Format
Function...

"If you try to format a number without specifying format, Format
provides functionality similar to the Str function, although it is
internationally aware. However, positive numbers formatted as
strings using Format don’t include a leading space reserved for
the sign of the value; those converted using Str retain the leading
space."

Rick
 
Thanks for the replies - they were very helpful!

You can also use the Format function (although, since we know we want a
String value back, I would use Format$ of the function instead).

x = 1

Format$(x) = "1" --- evaluates to True

This is documented in the Remarks section of the help file for the Format
Function...

"If you try to format a number without specifying format, Format
provides functionality similar to the Str function, although it is
internationally aware. However, positive numbers formatted as
strings using Format don't include a leading space reserved for
the sign of the value; those converted using Str retain the leading
space."

Rick
 

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

Similar Threads


Back
Top