How to remove the last character from integer value in vb6

Viewed 73

Hello i am trying to make a code that removes the last digit from an integer example

int num = 1234

to be

int num 123

I did the same code in C# but i am failing to do it on vb6 this is the c# code.

num = num.Remove(num.length -1)

on vb6 i tried something like this

num = Len(num) -1 

but all it does is from

num = 1234

it makes it

num = 1233

or just shows

num = 3 

since removed the 4th digit

2 Answers

You are on the right path. The key missing step is to convert the number to a string before manipulating it.

Option Explicit

Private Sub Command1_Click()
   Dim num As Integer
   Dim s As String
   
   num = 1234
   s = CStr(num)              'convert number to a string
   s = Left(s, Len(s) - 1)    'remove last digit
   num = CInt(s)              'convert string back to a number
   
   Debug.Print num
End Sub

The error in your code is using Len on an Integer. From the documentation:

Returns a Long containing the number of characters in a string or the number of bytes required to store a variable.

You can simply divide your number by 10:

Function TrimInteger(number As Integer) As Integer
    TrimInteger = Int(number / 10)
End Function

Int is used to remove the fractional part of the division result and return the resulting integer value.

You can also declare number and the Function's return type as a Long instead of an Integer to support larger numbers:

Function TrimNumber(number As Long) As Long
    TrimNumber = Int(number / 10)
End Function
Related