Int.TryParse() returns false always

2019-02-17 22:42发布

问题:

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 ?

回答1:

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.



回答2:

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.



回答3:

Use MaxLength property to limit the number of digits and user cannot enter more than int32.

TextBox.MaxLength=9  


回答4:

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



回答5:

You should use long instead of int. Your number is too large for int



回答6:

Use long.TryParse()

Your number is too large to convert into int.

or you can use int64.tryparse