vb.net 强制整数为两位数 - VB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25568482/
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
Force an integer to be two digits - VB
提问by Lakshmi Narasimhan Ravichandra
I have a variable that holds a string "02100030000000000000000000D5010008D501000804"and I'm byte separating the string using
我有一个保存字符串的变量,"02100030000000000000000000D5010008D501000804"我使用字节分隔字符串
For i As Integer = 1 To (stringReader.Length - 1) Step 2
'Get the successive 2-character substrings, parse as bytes and add to total
Dim b As Byte = Byte.Parse(stringReader.Substring(i, 2), NumberStyles.AllowHexSpecifier)
sum = sum + CInt(b)
Next
I'm converting the strings to direct integers.e.g:(string"10" to Integer10 and ). That works fine. But Whenever I convert the string"02" to Integer, I get only Integer(2) and I need Integer(02). How can I proceed with?
我正在将字符串转换为直接整数。例如:(string"10" to Integer10 and )。这很好用。但是每当我将字符串“02”转换为 Integer 时,我只得到 Integer(2) 而我需要 Integer(02)。我该如何继续?
My code is:
我的代码是:
stringReader = fileReader.ReadLine()
byt = stringReader(1) + stringReader(2)
stringreader contains something like "100030000000000000000000D5010008D501000804"
stringreader 包含类似的东西 "100030000000000000000000D5010008D501000804"
Byte separation
字节分离
For i As Integer = 1 To (stringReader.Length - 1) Step 2
'Get the successive 2-character substrings, parse as bytes and add to total
Dim b As Byte = Byte.Parse(stringReader.Substring(i, 2), NumberStyles.AllowHexSpecifier)
sum = sum + CInt(b)
Next
回答by Tim Schmelter
You can use
您可以使用
number.ToString("D2")
where numberis an integral type like System.Int32(Integer).
其中number是像System.Int32( Integer)这样的整数类型。
Further reading: Standard Numeric Format Strings: The Decimal ("D") Format Specifier
进一步阅读:标准数字格式字符串:十进制(“D”)格式说明符
If you have a Stringinstead you could also use String.PadLeft:
如果你有一个,String你也可以使用String.PadLeft:
"2".PadLeft(2, "0"c) ' -> "02"

