Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse equivalent of Convert with invariantculture

In my code I frequently use the following Converts:

Convert.ToInt32(value, Cultureinfo.InvariantCulture);
Convert.ToDecimal(value, CultureInfo.InvariantCulture);

I now do like to use TryParse functions because of recent errors. I'm not entirely sure if i'm correct in using the following equivalents as I do not completely understand the NumberStyles enum.

Int64.TryParse(value, NumberStyles.Any, CultureInfo.invariantCulture, out output);
Decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out output);

EDIT BELOW after answers

The following code should then be the correct alternative:

Int64.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out output);
Decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out output);
like image 723
Schuere Avatar asked May 22 '15 10:05

Schuere


2 Answers

You can read about NumberStyles in the documentation. Essentially it allows you to specify what sort of text will parse.

If you want to be as flexible as possible, then NumberStyles.Any is the 'widest' option.

Convert.ToInt32 is equivalent to using int.Parse and Convert.ToDecimal is equivalent to using decimal.Parse - they delegate to these methods.

Per the documentation for int.Parse, the default is NumberStyles.Integer. And per the documentation for decimal.Parse, the default is NumberStyles.Number. If you want to be consistent with the behaviour of Convert.ToInt32 and Convert.ToDecimal, you should use these values.

like image 196
Charles Mager Avatar answered Sep 18 '22 17:09

Charles Mager


The documentation for Int64.TryParse says NumberStyles.Integer is the default:

The s parameter is interpreted using the NumberStyles.Integer style. In addition to the decimal digits, only leading and trailing spaces together with a leading sign are allowed.

For Decimal.TryParse, it's NumberStyles.Number:

Parameter s is interpreted using the NumberStyles.Number style. This means that white space and thousands separators are allowed but currency symbols are not.

like image 29
dcastro Avatar answered Sep 17 '22 17:09

dcastro