문자열을 int로 어떻게 변환 할 수 있습니까?
-
06-07-2019 - |
문제
나는있다 TextBoxD1.Text
그리고 나는 그것을 an으로 변환하고 싶습니다 int
데이터베이스에 저장합니다.
어떻게 할 수 있습니까?
해결책
이 시도:
int x = Int32.Parse(TextBoxD1.Text);
또는 더 나은 것 :
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
또한 그 이후로 Int32.TryParse
반환 a bool
반품 값을 사용하여 구문 분석 시도 결과에 대한 결정을 내릴 수 있습니다.
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
당신이 궁금하다면, 차이 Parse
그리고 TryParse
다음과 같이 가장 잘 요약됩니다.
TryParse 메소드는 변환이 실패한 경우 TryParse 메소드가 예외를 던지지 않는다는 점을 제외하고는 구문 분석 방법과 같습니다. 예외 처리를 사용하여 S가 유효하지 않고 성공적으로 구문 분석 할 수없는 경우 Formatexception을 테스트 할 필요가 없습니다. - MSDN
다른 팁
Convert.ToInt32( TextBoxD1.Text );
텍스트 상자의 내용이 유효한 int라고 확신한다면 이것을 사용하십시오. 더 안전한 옵션입니다
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
이렇게하면 사용할 수있는 기본값이 제공됩니다. Int32.TryParse
또한 부울 값을 반환하여 구문 분석 할 수 있는지 여부를 나타내므로이를 if
성명.
if( Int32.TryParse( TextBoxD1.Text, out val ){
DoSomething(..);
} else {
HandleBadInput(..);
}
int.TryParse()
텍스트가 숫자가 아닌 경우에는 던지지 않습니다.
int myInt = int.Parse(TextBoxD1.Text)
또 다른 방법은 다음과 같습니다.
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
둘 사이의 차이점은 텍스트 상자의 값을 변환 할 수없는 경우 첫 번째는 예외를 던지고 두 번째는 False를 반환한다는 것입니다.
문자열을 구문 분석해야하며 문자열이 진정으로 정수 형식인지 확인해야합니다.
가장 쉬운 방법은 다음과 같습니다.
int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}
int x = 0;
int.TryParse(TextBoxD1.Text, out x);
TryParse 성명서는 구문 분석이 성공했는지 여부를 나타내는 부울을 반환합니다. 성공하면 구문 분석 값이 두 번째 매개 변수에 저장됩니다.
보다 int32.tryparse 메소드 (String, int32) 더 자세한 정보는.
즐기세요 ...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
여기에는 이미 많은 해결책이 있습니다 int.Parse
, 모든 답변에는 중요한 것이 있습니다. 일반적으로 숫자 값의 문자열 표현은 배양에 따라 다릅니다. 통화 기호, 그룹 (또는 수천) 분리기 및 소수 분리기와 같은 숫자 문자열의 요소는 모두 문화에 따라 다릅니다.
정수에 문자열을 구문 분석하는 강력한 방법을 만들려면 문화 정보를 고려하는 것이 중요합니다. 그렇지 않으면 현재 문화 설정 사용하게 될 것이다. 그것은 파일 형식을 구문 분석하는 경우 사용자에게 꽤 불쾌한 놀라움을 줄 수 있습니다. 영어 구문 분석을 원한다면 사용할 문화 설정을 지정하여 단순히 명시 적으로 만드는 것이 가장 좋습니다.
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
// use result...
}
자세한 내용은 CultureInfo, 구체적으로 읽으십시오. 숫자 포르 아인포 MSDN에서.
char에 convert.toint32 ()를 사용할 때 조심하십시오!
반환합니다 UTF-16 캐릭터의 코드!
문자열에 액세스하는 경우 [i]
인덱싱 연산자 a char
그리고 아니다 string
!
String input = "123678";
int x = Convert.ToInt32(input[4]); // returns 55
int x = Convert.ToInt32(input[4].toString()); // returns 7
자신만의 확장 방법을 쓸 수 있습니다
public static class IntegerExtensions
{
public static int ParseInt(this string value, int defaultValue = 0)
{
int parsedValue;
if (int.TryParse(value, out parsedValue))
{
return parsedValue;
}
return defaultValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return value.ParseInt();
}
}
그리고 코드가 어디에 있든 전화하십시오
int myNumber = someString.ParseInt(); // returns value or 0
int age = someString.ParseInt(18); // with default value 18
int? userId = someString.ParseNullableInt(); // returns value or null
이 구체적인 경우
int yourValue = TextBoxD1.Text.ParseInt();
설명 된 바와 같이 tryparse 문서, tryparse ()는 부울을 반환하여 유효한 숫자가 발견되었음을 나타냅니다.
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// put val in database
}
else
{
// handle the case that the string doesn't contain a valid number
}
당신은 둘 중 하나를 사용할 수 있습니다.
int i = Convert.ToInt32(TextBoxD1.Text);
또는
int i =int.Parse(TextBoxD1.Text);
변환 string
에게 int
다음을 수행 할 수 있습니다. int
, Int32
, Int64
.NET의 정수 데이터 유형을 반영하는 기타 데이터 유형
아래 예제는이 변환을 보여줍니다.
이 쇼 (정보 용) 데이터 어댑터 요소는 int 값으로 초기화되었습니다. 직접적으로 동일하게 수행 할 수 있습니다.
int xxiiqVal = Int32.Parse(strNabcd);
전.
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
//May be quite some time ago but I just want throw in some line for any one who may still need it
int intValue;
string strValue = "2021";
try
{
intValue = Convert.ToInt32(strValue);
}
catch
{
//Default Value if conversion fails OR return specified error
// Example
intValue = 2000;
}
이것은 할 것입니다
string x=TextBoxD1.Text;
int xi=Convert.ToInt32(x);
또는 사용할 수 있습니다
int xi=Int32.Parse(x);
다음을 사용하여 문자열을 c#에서 int로 변환 할 수 있습니다.
Convert Class IE의 기능 Convert.ToInt16()
, Convert.ToInt32()
, Convert.ToInt64()
또는 사용하여 Parse
그리고 TryParse
기능. 예제가 제공됩니다 여기.
또한 사용할 수도 있습니다 확장 방법, 더 읽기 쉬워 질 것입니다 (모든 사람이 이미 일반 구문 분석 기능에 익숙하지만).
public static class StringExtensions
{
/// <summary>
/// Converts a string to int.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The converted integer.</returns>
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Checks whether the value is integer.
/// </summary>
/// <param name="value">The string to check.</param>
/// <param name="result">The out int parameter.</param>
/// <returns>true if the value is an integer; otherwise, false.</returns>
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
그런 다음 그런 식으로 부를 수 있습니다.
당신의 줄이 "50"과 같은 정수인지 확실하다면.
int num = TextBoxD1.Text.ParseToInt32();
확실하지 않고 충돌을 방지하고 싶다면.
int num; if (TextBoxD1.Text.TryParseToInt32(out num)) { //The parse was successful, the num has the parsed value. }
더 역동적으로 만들려면 두 배의 플로트 등을 구문 분석 할 수 있습니다. 일반적인 확장을 만들 수 있습니다.
TryParse 또는 내장 기능없이 아래에서 좋아할 수 있습니다.
static int convertToInt(string a)
{
int x=0;
for (int i = 0; i < a.Length; i++)
{
int temp=a[i] - '0';
if (temp!=0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x ;
}
int i = Convert.ToInt32(TextBoxD1.Text);
내가 항상하는 방식은 다음과 같습니다
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example_string_to_int
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
// this turns the text in text box 1 into a string
int b;
if (!int.TryParse(a, out b))
{
MessageBox.Show("this is not a number");
}
else
{
textBox2.Text = a+" is a number" ;
}
// then this if statment says if the string not a number display an error elce now you will have an intager.
}
}
}
이것이 내가하는 방법입니다. 이것이 도움이되기를 바랍니다. (:
구문 분석 방법을 사용하여 문자열을 정수 값으로 변환 할 수 있습니다.
예 :
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
당신은 이것을 시도 할 수 있습니다. 작동합니다.
int x = Convert.ToInt32(TextBoxD1.Text);
변수 textboxd1.text의 문자열 값은 int32로 변환되며 x에 저장됩니다.
먼 길을 찾고 있다면 하나의 방법을 만듭니다.
static int convertToInt(string a)
{
int x = 0;
Char[] charArray = a.ToCharArray();
int j = charArray.Length;
for (int i = 0; i < charArray.Length; i++)
{
j--;
int s = (int)Math.Pow(10, j);
x += ((int)Char.GetNumericValue(charArray[i]) * s);
}
return x;
}
방법 1
int TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
Console.WriteLine("String not Convertable to an Integer");
}
방법 2
int TheAnswer2 = 0;
try {
TheAnswer2 = Int32.Parse("42");
}
catch {
Console.WriteLine("String not Convertable to an Integer");
}
방법 3
int TheAnswer3 = 0;
try {
TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
Console.WriteLine("String is null");
}
catch (OverflowException) {
Console.WriteLine("String represents a number less than"
+ "MinValue or greater than MaxValue");
}
이 코드는 Visual Studio 2010에서 저를 위해 작동합니다.
int someValue = Convert.ToInt32(TextBoxD1.Text);
이것은 당신에게 도움이 될 수 있습니다; d
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float Stukprijs;
float Aantal;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
}
private void button1_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
errorProvider2.Clear();
if (float.TryParse(textBox1.Text, out Stukprijs))
{
if (float.TryParse(textBox2.Text, out Aantal))
{
float Totaal = Stukprijs * Aantal;
string Output = Totaal.ToString();
textBox3.Text = Output;
if (Totaal >= 100)
{
float korting = Totaal - 100;
float korting2 = korting / 100 * 15;
string Output2 = korting2.ToString();
textBox4.Text = Output2;
if (korting2 >= 10)
{
textBox4.BackColor = Color.LightGreen;
}
else
{
textBox4.BackColor = SystemColors.Control;
}
}
else
{
textBox4.Text = "0";
textBox4.BackColor = SystemColors.Control;
}
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
else
{
errorProvider1.SetError(textBox1, "Bedrag plz!");
if (float.TryParse(textBox2.Text, out Aantal))
{
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
}
private void BTNwissel_Click(object sender, EventArgs e)
{
//LL, LU, LR, LD.
Color c = LL.BackColor;
LL.BackColor = LU.BackColor;
LU.BackColor = LR.BackColor;
LR.BackColor = LD.BackColor;
LD.BackColor = c;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
}
}
}