Search code examples
c#visual-studiotype-conversion.net-framework-version

int.TryParse(String, NumberStyles, IFormatProvider, Int32) on .NET 6.0


This question was about IFormatProvider argument on int.TryParse

CultureInfo.CurrentCulture is passed to IFormatProvider to avoid culture related issues e.g 5.2 means decimal in some countries but in some it is thousand.

Why is this important? NumberStyles argument behaves regarding the CultureInfo e.g NumberStyles.AllowThousands detects the thousand regarding the culture info.

I deleted the question body because It was my fault and it was misleading (see below) and left what is important to upcoming developers.

my mistake:I was getting 5.0 even though it was an int and I couldn't figure out why. It was because of my culture info.


Solution

  • Your code is correct, however I suspect your current culture uses something other than a period (.) as a decimal separator. It looks like you may be in Turkey based on your link to the MSDN, in which case the decimal separator is a comma (,).

    The below examples should help you figure out what is best to do in your use case.

    // Build the number string using the current culture decimal separator
    var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    string numberString = $"5{decimalSeparator}0";
    bool valid = int.TryParse(numberString, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out int result);
    
    // Use a culture that uses a period as a decimal separator
    string numberString = "5.0";
    bool valid = int.TryParse(numberString, NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("en-GB"), out int result);
    
    // Current culture must use a comma as a decimal separator
    string numberString = "5,0";
    bool valid = int.TryParse(numberString, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out int result);