Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int.TryParse() returns false always

Tags:

c#

tryparse

int32

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 ?

like image 305
Microsoft DN Avatar asked Dec 18 '15 06:12

Microsoft DN


2 Answers

The limit for int (32-bit integer) is -2,147,483,648 to 2,147,483,647. Your number is too large.

For large integer number such as your case, try to Parse using long.TryParse (or Int64.TryParse since Int64 is long in C#) instead. The limit for long number is of the range of -9.2e18 to 9.2e18*

long varOut;
long.TryParse(txt1.Text, out varOut); // Here txt1.Text = 4286656181793660  

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

decimal varOut;
decimal.TryParse(txt1.Text, out varOut); // Here txt1.Text = 4286656181793660  

It is 128-bit data type, with the range of -7.9e28 to 7.9e28, and 28-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. Although double has a very high range of ±5.0 × 10e−324 to ±1.7 × 10e308, its precision is only about 15-16 digits (reference).

double varOut;
double.TryParse(txt1.Text, out varOut); // Not a good idea... since the input number is 16-digit Here txt1.Text = 4286656181793660  

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 to 9,223,372,036,854,775,807.

like image 101
Ian Avatar answered Nov 08 '22 11:11

Ian


int is just shorthand for int32; 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 valid int value.

like image 3
Servy Avatar answered Nov 08 '22 13:11

Servy