vb.net 将整数格式化为 2 位数的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34497827/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:11:42  来源:igfitidea点击:

Format integer as string with 2 digits

vb.netformat

提问by AntonioC

I would like to format the integer 9 to "09" and 25 to "25".

我想将整数 9 格式化为“09”,将 25 格式化为“25”。

Can somebody tell me how this can be done?

有人可以告诉我如何做到这一点吗?

Thank you!

谢谢!

采纳答案by durbnpoisn

I don't know the exact syntax. But in any language, it would look like this.

我不知道确切的语法。但在任何语言中,它看起来都像这样。

a = 9
aString =""

if a < 10 then 
  aString="0" + a 
else 
  aString = "" + a
end if

回答by Reza Aghaei

You can use either of these options:

您可以使用以下任一选项:

The "0" Custom Specifier

“0”自定义说明符

  • value.ToString("00")
  • String.Format("{0:00}", value)
  • value.ToString("00")
  • String.Format("{0:00}", value)

The Decimal ("D") Standard Format Specifier

十进制 ("D") 标准格式说明符

  • value.ToString("D2")
  • String.Format("{0:D2}", value)
  • value.ToString("D2")
  • String.Format("{0:D2}", value)

For more information:

想要查询更多的信息:

回答by Gavin Perkins

If its just leading zero's that you want, you can use this:

如果它只是你想要的前导零,你可以使用这个:

value.tostring.padleft("0",2)

If you have 2 digits, say 25 for example, you will get "25" back....if you have just one digit, say 9 for example, you will get "09"....It is worth noting that this gives you a string back, and not an integer, so you may need to cast this later on in your code.

如果你有2位数字,比如25,你会得到“25”......如果你只有一位数字,比如9,你会得到“09”......值得注意的是,这个给你一个字符串,而不是一个整数,所以你可能需要稍后在你的代码中转换它。