-2

I have a value "0001" as string.

So, how to insert the value to field with type data int?

I work in c#

example :
string val = "0001";
int getVal = val;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Or...http://stackoverflow.com/q/405619/327083 ; http://stackoverflow.com/q/952469/327083 ... Also, there is the painfully easy-to-find documentation : http://msdn.microsoft.com/en-us/library/bb397679.aspx – J... Jul 14 '14 at 08:33

5 Answers5

4

You can use Int32.Parse or Int32.TryParse methods. But remember, 0001 is just a textual representation of a number... i.e. a string. When you parse this string, you will get 1 not 0001. There is nothing 0001 as an int.

string val = "0001";
int getval;
if (Int32.TryParse(val, out getval))
{
     //Successfull parsing
}
else
{
     //Your string is not a valid integer.
}

Difference between these methods is; Int32.Parse throws FormatException if your string is not a valid Int32. But Int32.TryParse doesn't throw any exception in any case. It just returns false if parsing is not succeed.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • the return is "1".. i want to input in table "0001". – user3747046 Jul 14 '14 at 08:36
  • 1
    @user3747046 As I said, you can't have an `int` as a `0001`. Leading zeros are not allowed for integers. `0001` is just a `string` representation of it. What is "table" in your case? Is it a database table? If it is, then you can define your column type as a character (`nvarchar` for example) and you can insert `0001` value as a `string` without any parsing operation. – Soner Gönül Jul 14 '14 at 08:41
2

You can convert a string to an int by using int.Parse() or int.TryParse() which won't throw an exception if the parsing fails.

However be aware that 0001 and 1 are represented in the exact same way when converted to integer. If you require the trailing zeroes, then you have to retain the string and convert to an int only when you need to do calculations.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
2

Leading zeros are not allowed for integers, but maybe this article can help you

How to: Pad a Number with Leading Zeros

Narek
  • 459
  • 2
  • 13
0
int getVal;
string val = "0001";
Int.tryparse(val,out int getVal);

For more information http://www.codeproject.com/Articles/32885/Difference-Between-Int-Parse-Convert-ToInt-and is a tutorial

tell me any number that is 0001 and not 1? they are the same. It depends on how you print the number or store the number back in a string.

Charlie
  • 4,827
  • 2
  • 31
  • 55
0

Try this:

string val = "0001"; 
int getVal = Convert.ToInt32(val);
Arti
  • 2,993
  • 11
  • 68
  • 121