vb.net 如何在 Visual Basic 中将字符串转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7708838/
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
How do I convert from a string to an integer in Visual Basic?
提问by swydell
How do I convert from a string to an integer? Here's what I tried:
如何将字符串转换为整数?这是我尝试过的:
Price = CInt(Int(txtPrice.Text))
I took out the Int
and I still got an exception.
我拿出了Int
,我仍然有一个例外。
回答by Chad Schouggins
Use
用
Convert.toInt32(txtPrice.Text)
This is assuming VB.NET.
这是假设VB.NET。
Judging by the name "txtPrice", you really don't want an Integer but a Decimal. So instead use:
从名称“txtPrice”来看,您确实不需要整数而是小数。所以改为使用:
Convert.toDecimal(txtPrice.Text)
If this is the case, be sure whatever you assign this to is Decimal not an Integer.
如果是这种情况,请确保您将其分配给 Decimal 而不是 Integer。
回答by zari
You can try it:
你可以试试看:
Dim Price As Integer
Int32.TryParse(txtPrice.Text, Price)
回答by Srinivasan
You can use the following to convert string to int:
您可以使用以下命令将字符串转换为 int:
- CInt(String) for ints
- CDec(String) for decimals
- 整数的 CInt(String)
- CDec(String) 表示小数
For details refer to Type Conversion Functions (Visual Basic).
有关详细信息,请参阅类型转换函数 (Visual Basic)。
回答by Moola TK
Please try this, VB.NET 2010:
请试试这个,VB.NET 2010:
Integer.TryParse(txtPrice.Text, decPrice)
decPrice = Convert.ToInt32(txtPrice.Text)
Integer.TryParse(txtPrice.Text, decPrice)
decPrice = Convert.ToInt32(txtPrice.Text)
From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)
来自 Mola Tshepo Kingsley (WWW.TUT.AC.ZA)
回答by Majosty D
You can try these:
你可以试试这些:
Dim valueStr as String = "10"
Dim valueIntConverted as Integer = CInt(valueStr)
Another example:
另一个例子:
Dim newValueConverted as Integer = Val("100")
回答by Nandostyle
Use Val(txtPrice.text)
使用 Val(txtPrice.text)
I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.
我还可以通过在价格文本框的按键事件中插入一些验证代码来只允许数字和点字符。
回答by stuartdotnet
Convert.ToIntXX doesn't like being passed strings of decimals.
Convert.ToIntXX 不喜欢传递小数字符串。
To be safe use
为了安全使用
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))