Invariant culture equivalent TryParse Convert

In my code, I often use the following converters:

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

Now I like to use TryParse functions due to recent errors. I'm not quite sure if I am using the following equivalents correctly, as I do not fully understand the NumberStyles enumeration.

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

CHANGE BELOW after replies

The following code should be the correct alternative:

 Int64.TryParse(value, NumberStyles.Integer, CultureInfo.invariantCulture, out output); Decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out output); 
+6
source share
3 answers

You can read about NumberStyles in the documentation. In essence, this allows you to determine which text will be analyzed.

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

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

The documentation for int.Parse defaults to NumberStyles.Integer . And for documentation for decimal.Parse , the default is NumberStyles.Number . If you want to be compatible with the behavior of Convert.ToInt32 and Convert.ToDecimal , you must use these values.

+7
source

The documentation for Int64.TryParse says NumberStyles.Integer by default:

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

For Decimal.TryParse , it NumberStyles.Number :

The s parameter is interpreted using the NumberStyles.Number style. This means that spaces and thousands separators are allowed, but currency symbols are not.

+4
source

Yes, your approach is correct, both approaches should give the same results.

The implementation of Convert.ToInt32(string s) is as follows:

 public static int ToInt32(String value, IFormatProvider provider) { if (value == null) return 0; return Int32.Parse(value, NumberStyles.Integer, provider); } 

So, as you can see inside, one method calls another - the only difference is that with Convert you have no control over the style of the number - it is tightly bound to NumberStyles.Integer . If you need identical functionality, you must specify this enumeration value in your TryParse calls.

The source code for the Convert class is available here .

Can I also indicate that you are calling Int64.TryParse if Convert.ToInt32 was enough, so there should be Int32.TryParse .

+2
source

Source: https://habr.com/ru/post/987731/


All Articles