When would it make sense to use int32.Parse(String, IFormatProvider)
?
As far as I can tell, this and int32.Parse(String)
uses NumberStyles.Integer
anyway which only allows a plus, a minus, or digits, optionally surrounded by whitespace, so why does the locale format enter into the equation?
I know about thousand separators, but they don't matter because NumberStyles.Integer
disallows them no matter your region.
Consider if you have culture where negative sign is M
(minus). I am pretty sure it doesn't exist but just consider that you have something like that. Then you can do:
string str = "M123";
var culture = new CultureInfo("en-US");
culture.NumberFormat.NegativeSign = "M";
int number = Int32.Parse(str, culture);
This would result in -123
as value. This is where you can use int32.Parse(String, IFormatProvider)
overload. If you don't specify the culture, then it would use the current culture and would fail for the value M123
.
(Old Answer)
It is useful with string with thousand separator
Consider the following example,
string str = "1,234,567";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
int number = Int32.Parse(str, CultureInfo.CurrentCulture);
This would result in an exception since .
is the thousand separator in German culture.
For
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
The above would parse successfully, since the German culture uses .
as thousand separator.
But if you have current culture set as US then it would give an exception.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
See: Int32.Parse Method (String, IFormatProvider)
The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information about the format of s. If provider is null, the NumberFormatInfo object for the current culture is used.
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