Truncating numbers

D

Dirk Goldgar

Tequila said:
How can I truncate a number? 123456 truncate 12 result=3456

Thanks,
John

If I understand you, that's really a text operation -- dropping the
leading two digits from the front of the string of decimal digits that
represent the value. So you'd convert it to a string from its internal
numeric representation, drop the digits, and convert the resulting
string back to a number. For example,

Dim lngNumber As Long
Dim strDigits As String

lngNumber = 123456

strDigits = CStr(lngNumber)

If Len(strDigits) > 2 Then
lngNumber = CLng(Mid(strDigits, 3))
Else
lngNumber = 0
End If
 
D

Douglas J. Steele

Dirk Goldgar said:
If I understand you, that's really a text operation -- dropping the
leading two digits from the front of the string of decimal digits that
represent the value. So you'd convert it to a string from its internal
numeric representation, drop the digits, and convert the resulting
string back to a number. For example,

Dim lngNumber As Long
Dim strDigits As String

lngNumber = 123456

strDigits = CStr(lngNumber)

If Len(strDigits) > 2 Then
lngNumber = CLng(Mid(strDigits, 3))
Else
lngNumber = 0
End If

Not wanting to seem argumentative, it could also be done using Mod.

To drop the first 2 digits of a 6 digit number, you could use:

Dim lngNumber As Long

lngNumber = 123456

lngNumber = lngNumber Mod 10000
 
D

Dirk Goldgar

Douglas J. Steele said:
Not wanting to seem argumentative, it could also be done using Mod.

To drop the first 2 digits of a 6 digit number, you could use:

Dim lngNumber As Long

lngNumber = 123456

lngNumber = lngNumber Mod 10000


True, o king. But if you don't know how many digits there will be in
the number, doing it via Mod would involve either a set of graduated If
.... ElseIf statements, or else formatting it into a string anyway to
check the number of digits. I was assuming the number of digits
wouldn't be known in advance. I guess the choice of approach is likely
to depend on things we don't know.
 
Top