5

I am converting an integer to string using the str() function

However, I noticed that the str() function would return an extra character to the string.

For example, MsgBox(Len(str(1))) would return 2.

What is the extra character being appended?

Community
  • 1
  • 1
Steveng
  • 1,451
  • 4
  • 15
  • 14
  • 2
    Doug Glancy's quote is correct although I would have added the next line: "Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. _Unlike Str, the Format function doesn't include a leading space for the sign of number_." [My italics] – Tony Dallimore Apr 04 '12 at 08:44
  • 1
    And if you want to trim that extra blank space, you can always use this `MsgBox (Len(Trim(Str(1))))` – Siddharth Rout Apr 04 '12 at 10:27
  • 1
    Use `Cstr(1)` rather than `Str(1)`. Cstr does not add a space. – HackSlash Feb 24 '21 at 23:57

3 Answers3

10

From Excel 2010 help:

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

And sure enough this statement returns True in the debug window:

? left(str(1),1) = " "
Doug Glancy
  • 27,214
  • 6
  • 67
  • 115
0

Easiest way to find out:

MsgBox(Asc(Right(Str(1),1)))
Ariel
  • 404
  • 2
  • 4
0

As pointed out in this answer you should use the format() function.

Community
  • 1
  • 1
fileinsert
  • 431
  • 4
  • 22