Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell if string to double/float/int/short/byte is out of range

I have the following:

string outOfRange = "2147483648"; // +1 over int.MaxValue

Obviously if you have anything other than a number this will fail:

var defaultValue = 0;
int.TryParse(outOfRange, out defaultValue);

My question is, since this IS a number, and it WILL fail when you int.TryParse(), how do you tell that it failed because the string was out of the bounds of the container it's stored in?

like image 672
gleng Avatar asked Aug 29 '13 19:08

gleng


2 Answers

I'd go with the Try/Catch solution for this scenario.

        string outOfRange = "2147483648";
        try
        {
            int.Parse(outOfRange);
        }
        catch (OverflowException oex)
        {

        }
        catch (Exception ex)
        { }

I know that most people here would recommend avoiding this but sometimes we just have to use it (or we don't have to but it would just save us a lot of time).
here's a little post about the efficiency of Try/Catch.

like image 80
Yoav Avatar answered Oct 25 '22 21:10

Yoav


can parse to decimal and then check range, avoids try/catch

string s = "2147483648";
decimal.Parse(s) > int.MaxValue;
like image 3
Konstantin Avatar answered Oct 25 '22 19:10

Konstantin