I have following code
int varOut;
int.TryParse(txt1.Text, out varOut); // Here txt1.Text = 4286656181793660
Here txt1.Text is the random 16 digit number generated by JavaScript which is an integer. But the above code always return false i.e. varOut value is always zero.
What I am doing wrong here ?
Use
MaxLength
property to limit the number of digits and user cannot enter more thanint32
.int
is just shorthand forint32
; it's a 32 bit (signed) integer, meaning that it can't hold a number larger than around 2 billion. Your number is larger than that, and so is not a validint
value.You should use
long
instead ofint
. Your number is too large forint
The limit for
int
(32-bit
integer) is-2,147,483,648
to2,147,483,647
. Your number is too large.For large
integer
number such as your case, try toParse
usinglong.TryParse
(orInt64.TryParse
sinceInt64
islong
in C#) instead. The limit forlong
number is of the range of-9.2e18 to 9.2e18
*It should be sufficient for your number, which is only around
4.2e15
(4,286,656,181,793,660
).Alternatively, you may want to consider using
decimal.TryParse
if you want to have decimal number (containing fraction, higher precision).It is
128-bit
data type, with the range of-7.9e28 to 7.9e28
, and28-29
significant digits precision, fits best for any calculation involving money.And, as a last remark to complete the answer, it may be unsafe to use
double
- do not use it. Althoughdouble
has a very high range of±5.0 × 10e−324 to ±1.7 × 10e308
, its precision is only about 15-16 digits (reference).In this case, your number consists of 16 digits, which is in the borderline of the
double
precision. Thus, in some cases, you may end up with wrong result. Only if you are sure that your number will be at most 15-digit precision that you are safe to use it.*
-9,223,372,036,854,775,808
to9,223,372,036,854,775,807
.Looks like you may be using value(s) which exceed the capacity of the type you're using... look at https://msdn.microsoft.com/en-us/library/system.int32.maxvalue%28v=vs.110%29.aspx
Store it as a long instead of an int. https://msdn.microsoft.com/en-us/library/ctetwysk.aspx
Use long.TryParse()
Your number is too large to convert into int.
or you can use int64.tryparse