Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Int32.TryParse returns false for number?

I have this code:

string sPhone = "420777777777";
int rPhone;
bool valid = Int32.TryParse(sPhone, out rPhone); //false
if (!valid)
 return "";
return String.Format("{0:+### ### ### ###}", rPhone);

I want to format phone number so I'm converting string to int, but value of valid is always false. How can I convert this string to int? I was also trying int.TryParse or Convert.ToInt32. Nothing worked.

like image 662
BblackK Avatar asked Jun 05 '26 12:06

BblackK


1 Answers

Because Int32.MaxValue is 2147483647 so, the conversion of your string "420777777777" will never be a valid value for an Int32 ;

Use

string sPhone = "420777777777";
long rPhone;
bool valid = Int64.TryParse(sPhone, out rPhone); 
return (!valid ? "" : string.Format("{0:+### ### ### ###}", rPhone));  
like image 58
Steve Avatar answered Jun 07 '26 23:06

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!