How to get the first x leftmost digits of an integer number in VB.NET

1 Answer

0 votes
Imports System

Public Class FirstXLeftmostDigits_VB_NET
    Public Shared Sub Main(ByVal args As String())
        Dim rand As Random = New Random()

        For i As Integer = 1 To 5
            Dim n As Integer = rand.Next(100000) + 1
            Dim x As Integer = rand.Next(5) + 1
            Console.WriteLine(x & " leftmost digit of " & n & " is " & xLeftmostDigit(n, x))
        Next
    End Sub

    Public Shared Function xLeftmostDigit(ByVal n As Integer, ByVal x As Integer) As Integer
		x = CInt(Math.Pow(10, x))        
		While n > x
            n = n / 10
        End While

        Return n
    End Function
End Class



' run:
' 
' 4 leftmost digit of 14217 is 1422
' 1 leftmost digit of 19524 is 2
' 5 leftmost digit of 89654 is 89654
' 5 leftmost digit of 5488 is 5488
' 2 leftmost digit of 29444 is 29
'

 



answered Dec 7, 2024 by avibootz
edited Dec 8, 2024 by avibootz

Related questions

...