Results 1 to 7 of 7

Thread: Finding the value of the nth digit of a number

Threaded View

  1. #1

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    Finding the value of the nth digit of a number

    EyeRmonkey,I told you it couldn't be done in a single formula(which is a dead lie in hindsight...), simply because the number of operations you have to do changes depending on the length of the number and what digit you're looking for(not really...i was dumb when i wrote this post).

    If you want the code I came up with, here it is for ya. Fairly simple, actually. Enjoy!


    VB Code:
    1. Private Sub Command1_Click()
    2.  
    3.     'Text1 is the number you would like searched
    4.     'Text2 is the digit you are looking for
    5.     'Command1.... do I need to comment on that?
    6.     'Label1 tells you what the answer is
    7.      
    8.    
    9.     'The problem is simple... Given any number, what is the value of the nth
    10.     'digit from the right? eg x=45364, n=3. What is the value of the third digit
    11.     'from the right? Obviously, by looking at it, it's 3. But if for some odd
    12.     'reason you can't see the number, this program will figure it out for you.
    13.     'Cheers!
    14.  
    15.     Dim x As Long
    16.     Dim s As Integer
    17.     Dim i As Integer
    18.     Dim counter As Integer
    19.      
    20.     s = Len(Text1.Text) 'number of digits in the number
    21.     n = Val(Text2.Text) 'position from the right you want to know
    22.     x = Text1.Text 'your original number
    23.      
    24.     For counter = s To n + 1 Step -1
    25.         x = x - (Int((x / (10 ^ (counter - 1)))) * (10 ^ (counter - 1)))
    26.     Next counter 'presto chango... all numbers in front of your digit are removed
    27.      
    28.     x = Int(x / (10 ^ (n - 1))) 'abra kadabra, all numbers behind yours are gone
    29.      
    30.     Label1.Caption = x 'and the magic number mystically appears in the label
    31.      
    32. End Sub
    Last edited by timeshifter; Dec 9th, 2005 at 09:25 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width