首页 文章

如何将String转换为Int?

提问于
浏览
473

我有 TextBoxD1.Text 并且我想将其转换为 int 以将其存储在数据库中 .

我怎样才能做到这一点?

28 回答

  • 0

    您可以使用以下命令将字符串转换为C#中的int:

    转换类的函数,即 Convert.ToInt16()Convert.ToInt32()Convert.ToInt64() 或使用 ParseTryParse 函数 . 示例给出here .

  • 8
    int.TryParse()
    

    如果文本不是数字,它将不会抛出 .

  • 809

    如果您正在寻找漫长的道路,只需创建一个方法:

    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;
        }
    
  • 2
    int i = Convert.ToInt32(TextBoxD1.Text);
    
  • 8
    //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;
    }
    
  • 15

    我一直这样做的方式是这样的

    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.
            }
        }
    }
    

    这是我会怎么做,我希望这有帮助 . (:

  • 42

    虽然这里已经有很多描述 int.Parse 的解决方案,但在所有答案中都有一些重要的缺失 . 通常,数值的字符串表示因文化而异 . 数字字符串的元素(如货币符号,组(或千位)分隔符和小数分隔符)均因文化而异 .

    如果要创建一个将字符串解析为整数的强大方法,那么将使用current culture settings . 这可能会给用户带来一个非常令人讨厌的惊喜 - 或者更糟糕的是,如果你最好通过指定要使用的文化设置来明确地表达它:

    var culture = CultureInfo.GetCulture("en-US");
    int result = 0;
    if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
    {
        // use result...
    }
    

    有关更多信息,请阅读CultureInfo,特别是MSDN上的NumberFormatInfo .

  • 3

    你可以尝试这个,它会工作:

    int x = Convert.ToInt32(TextBoxD1.Text);
    

    变量TextBoxD1.Text中的字符串值将转换为Int32,并将存储在x中 .

  • 0

    这样做

    string x=TextBoxD1.Text;
    int xi=Convert.ToInt32(x);
    

    或者你可以使用

    int xi=Int32.Parse(x);
    

    参考Microsoft Developer Network for more information

  • 27

    如果没有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 ;
    }
    
  • 2

    您需要解析字符串,并且还需要确保它是真正的整数格式 .

    最简单的方法是:

    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
    }
    
  • 0

    此代码适用于Visual Studio 2010:

    int someValue = Convert.ToInt32(TextBoxD1.Text);
    
  • 8

    你可以使用其中之一,

    int i = Convert.ToInt32(TextBoxD1.Text);
    

    要么

    int i =int.Parse(TextBoxD1.Text);
    
  • 2

    在char上使用Convert.ToInt32()时要小心!
    它将返回角色的UTF-16代码!

    如果使用 [i] 索引运算符仅在某个位置访问该字符串,它将返回 char 而不是 string

    String input = "123678";
    
    int x = Convert.ToInt32(input[4]);  // returns 55
    
    int x = Convert.ToInt32(input[4].toString());  // returns 7
    
  • -3

    试试这个:

    int x = Int32.Parse(TextBoxD1.Text);
    

    或者更好的是:

    int x = 0;
    
    Int32.TryParse(TextBoxD1.Text, out x);
    

    此外,由于Int32.TryParse返回 bool ,您可以使用其返回值来决定解析尝试的结果:

    int x = 0;
    
    if (Int32.TryParse(TextBoxD1.Text, out x))
    {
        // you know that the parsing attempt
        // was successful
    }
    

    如果你很好奇, ParseTryParse 之间的区别最好总结如下:

    TryParse方法与Parse方法类似,只是如果转换失败,TryParse方法不会抛出异常 . 它消除了在s无效且无法成功解析的情况下使用异常处理来测试FormatException的需要 . - MSDN

  • 0

    string 转换为 int 可以执行以下操作: intInt32Int64 和其他反映.NET中整数数据类型的数据类型

    以下示例显示了此转换:

    此show(for info)数据适配器元素初始化为int值 . 同样可以直接完成,如,

    int xxiiqVal = Int32.Parse(strNabcd);
    

    防爆 .

    string strNii = "";
    UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
    

    Link to see this demo .

  • 4
    int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
    
  • 0
    int x = 0;
    int.TryParse(TextBoxD1.Text, out x);
    

    TryParse语句返回一个布尔值,表示解析是否成功 . 如果成功,则解析的值将存储到第二个参数中 .

    有关更多详细信息,请参阅Int32.TryParse Method (String, Int32) .

  • 4

    方法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");
    }
    
  • 3

    You can write your own extesion method

    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();
        }
    }
    

    And wherever in code just call

    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
    

    In this concrete case

    int yourValue = TextBoxD1.Text.ParseInt();
    
  • 17
    int myInt = int.Parse(TextBoxD1.Text)
    

    另一种方式是:

    bool isConvertible = false;
    int myInt = 0;
    
    isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
    

    两者之间的区别在于,如果文本框中的值无法转换,则第一个将抛出异常,而第二个将返回false .

  • 10
    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(..);
    }
    
  • 3

    您可以在parse方法的帮助下将字符串转换为整数值 .

    例如:

    int val = Int32.parse(stringToBeParsed);
    int x = Int32.parse(1234);
    
  • 0

    TryParse documentation中所述,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
    }
    
  • 6

    这可能会对你有所帮助; 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.");
            }
        }
    }
    
  • 4

    好好享受...

    int i = 0;
    string s = "123";
    i =int.Parse(s);
    i = Convert.ToInt32(s);
    
  • 6

    最简单的方法是使用这样的扩展助手:

    public static class StrExtensions
    {
      public static int ToInt(this string s, int defVal = 0) => int.TryParse(s, out var v) ? v : defVal;
      public static int? ToNullableInt(this string s, int? defVal = null) => int.TryParse(s, out var v) ? v : defVal;
    }
    

    用法很简单:

    var x = "123".ToInt(); // 123
    var y = "abc".ToInt(); // 0
    
    string t = null;
    var z = t.ToInt(-1); // -1
    var w = "abc".ToNullableInt(); // null
    
  • 4

    您也可以使用extension method,因此它更具可读性(尽管每个人都已经习惯了常规的Parse函数) .

    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.
    }
    

    为了使它更具动态性,所以你也可以将它解析为double,float等,你可以制作一个通用扩展 .

相关问题