iefpw
iefpw

Reputation: 7042

Parse any string number to number

I'm trying to found out if a string value is any kind of number. The numbers can be anything like $23.23, (232.3434), 34.4545, 64.345, 34.34%

For dollars and percentages I can remove the % and $ symbols from the string, but I can't get this number to get parsed using this code.

        string _number = "64.345";

        double _double;

        if (Double.TryParse(_number, NumberStyles.Any, null, out _double))
        {

        }
        else
        {
        }

What am I doing wrong in this code?

Upvotes: 2

Views: 89

Answers (2)

Ckrempp
Ckrempp

Reputation: 324

You could try and use the double.Parse() instead with a try catch statement, like this:

string _number = "64.345";

double _double;

try
{
   _double = Double.Parse(_number)
   // Other actions
}
catch (FormatException ex)
{
   // Actions for when invalid parameter is given for parse
}

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

What is your culture settings for your OS, it likely is misinterpreting the ..

If you passed in CultureInfo.InvariantCulture instead of null for the format provider that should solve your problem. When you pass in null it uses CultureInfo.CurrentCulture and your PC is set to a culture that does not interpret a . as a separator for decimal numbers.

Upvotes: 2

Related Questions