Best way to get the first digit from a variable integer in VB.NET

I am new to programming and need some help with the basics.

I have a function that takes an integer value. I want to be able to capture the first digit (or the first and second digits in some cases) of this integer and do something with it.

What is the best way to get the first digit of an integer (or first and second) in VB.NET?

+3
source share
5 answers
firstDigit = number.ToString().Substring(0,1)

firstTwoDigits = number.ToString().Substring(0,2);

int.Parse(firstDigit)

int.Parse(firstTwoDigits)

etc.

+16
source

I am not very versed in VB syntax, so I apologize for the syntax errors:

dim i as integer
while i >= 10
    i = i \ 10
end while
msgbox "i = " & i

Note. The number "first left" is printed. For example, for "12345" it prints "1".

+4

, , , , .

Dim n As Integer
n Mod 10

:

n Mod 100

.

, , , , .

+2

, :

  Dim number As Integer = 234734
  Dim first = number.ToString.ToCharArray()(0)

, :

 Dim number As Integer = 234734
 Dim second = number.ToString.ToCharArray()(1)
+1

. Math.ABS, , . , , ​​ , , .

Dim number As Integer = -107
Dim result As String
Dim numberFromLeft As Integer = 2

result = Math.Abs(number).ToString.Substring(0, numberFromLeft)

This results in 10, this is a string, but converting it back to a number is easy if you need to. If you need to keep track of whether it was positive or negative, you could use the original value to apply this return line to your collapsible line.

+1
source

Source: https://habr.com/ru/post/1715232/


All Articles