SINGLE variable question

A

A Mad Doberman

All:
I know how RIGHT, LEFT, and MID work....as I understand these
functions, they work with strings.
Is there a similar function that will work with non-strings, such as
SINGLE or INTEGER type variables?

Here's what I need.....I need to write some code to do some stuff
based on the last number in a SINGLE variable.

For example: Do this if the variable ends with a 1 (such as 25341) or
do that id the variable ends with a 3 (such as 23).

I suppose I could set a string variable equal to a Single variable,
then work with the string. However, I was looking for something a
little cleaner.
 
D

Doug Glancy

I believe you can just work with them:

Sub test()
Dim sngTest As Single
Dim intTest As Integer

sngTest = 5.423
intTest = 2341
Debug.Print Right$(sngTest, 2); " "; Right$(intTest, 3)
End Sub

hth,

Doug
 
R

RB Smissaert

Something like this will work for an integer or long number.
Doing this with a non-integer number such as a single will be more tricky.

Function GetLastXNumbersOfInteger(i As Integer, btLastXNumbers As Byte) As
Integer

Dim lDivider As Long

On Error GoTo ERROROUT

lDivider = 10 ^ btLastXNumbers
GetLastXNumbersOfInteger = i - ((i \ lDivider) * lDivider)

Exit Function
ERROROUT:

GetLastXNumbersOfInteger = -1

End Function


RBS
 
R

RyanH

You can convert the Variant DataType to a String using the Str Function.
Like so:

Sub ConvertNumber()

Dim myNumber As Single
Dim x As Long

myNumber = (2.9 / 45)

x = Right(Str(myNumber), 1)

End Sub

Hope this helps!
 
R

Rick Rothstein \(MVP - VB\)

Use the Mod operator with 10 as the modulus...

You posted in the programming group, so you are looking for VB code, right?

YourValue = 25341
LastDigit = YourValue Mod 10

But, if you actually wanted a worksheet formula....

=MOD(A1,10)

Rick
 
R

Rick Rothstein \(MVP - VB\)

Generalizing this approach in the same manner that RB did in his response...

Function GetLastXDigits(Value As Long, NumberOfDigits As Long) As Long
GetLastXDigits = Value Mod 10 ^ NumberOfDigits
End Function

Where you pass the number and how many ending digits you want into the
function.

Rick
 
R

RB Smissaert

I thought doing this with integer division and then multiplication would be
a bit faster than using Mod,
but just tested and Mod is slightly faster, plus it is neater as well.
Both are quite a bit faster than using string type manipulations, which
could matter if you are running this in a loop. Has to be a large loop
though to see the difference!

RBS
 

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