从 VB.NET 中不同长度的整数中获取第一个数字的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1281610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to get the first digit from an integer of varying length in VB.NET
提问by Cunners
I am a newbie to programming and need some help with the basics.
我是编程的新手,需要一些基础知识的帮助。
I have a function which takes in an integer value. I want to be able to grab 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 in VB.NET to get the first digit of an integer (or the first and second)?
在 VB.NET 中获取整数的第一个数字(或第一个和第二个)的最佳方法是什么?
回答by Xian
firstDigit = number.ToString().Substring(0,1)
firstTwoDigits = number.ToString().Substring(0,2);
int.Parse(firstDigit)
int.Parse(firstTwoDigits)
and so forth
等等
回答by Vilx-
I'm not well versed in VB syntax, so forgive me for the syntax errors:
我不精通VB语法,所以请原谅我的语法错误:
dim i as integer
while i >= 10
i = i \ 10
end while
msgbox "i = " & i
Note, this prints the "first from the left" digit. Like, for "12345" it would print "1".
请注意,这将打印“从左数第一个”数字。比如,对于“12345”,它会打印“1”。
回答by Yuval Adam
If you need the digits starting from the end of the integer, just get the modulu result for the tens or the hundreds, according to how many digits you need.
如果您需要从整数末尾开始的数字,只需根据您需要的数字数量获得十位或百位的模数结果。
Dim n As Integer
n Mod 10
for the first digit, or:
对于第一个数字,或:
n Mod 100
for the second and first digits.
对于第二位和第一位数字。
If you need the first and second digits from the beginning of the number, there is another answer here which will probably help you.
如果您需要数字开头的第一个和第二个数字,这里有另一个答案可能会对您有所帮助。
回答by Wael Dalloul
for first digit you can use:
对于第一个数字,您可以使用:
Dim number As Integer = 234734
Dim first = number.ToString.ToCharArray()(0)
for second digit you can use:
对于第二个数字,您可以使用:
Dim number As Integer = 234734
Dim second = number.ToString.ToCharArray()(1)
回答by CertifiedCrazy
This would work. You can use Math.ABS, absolute value, to eliminate negative. The number from left could be replaced by a function if you are using logic, like the overall length of the number, to determine how many of the leading characters you are going to use.
这会奏效。您可以使用 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 it is a string but converting it back to a number is easy if you need to. If you need to keep track if it was positive or negative you could use the original value to apply that back to you parsed string.
这导致 10 它是一个字符串,但如果需要,将其转换回数字很容易。如果您需要跟踪它是正数还是负数,您可以使用原始值将其应用回您解析的字符串。