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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With