0

I had to make a numeric pad in C# using windows forms that accepts and validates both double and int values, but the string format used for double is different between Windows 7 and 10. Those are the only operating systems I available I have for testing, and I came up with a solution that's way too restrict. The code is below and if it needs commentary, please ask me in the comments. Also if the question title sounds confusing or could be broader, please edit at will, I couldn't come up with anything better myself.

    private static readonly string WIN_10 = "Microsoft Windows NT 6.2.9200.0";
    private static readonly string WIN_7SP1 = "Microsoft Windows NT 6.1.7601 Service Pack 1";

    //(...)

    //Event handler for the comma/dot button:
    private void btDot_Click(object sender, EventArgs e)
    {
        var currentOS = Environment.OSVersion.VersionString;
        //"sb" is a StringBuilder object that holds what's being "typed" in the numpad
        if (sb.ToString().Contains(",") || sb.ToString().Contains(","))
            return;

        if (currentOS == WIN_7SP1)
            sb.Append(",");
        else if (currentOS == WIN_10)
            sb.Append(".");
        tbValue.Text = sb.ToString();
    }

    //(...)

Eventually, I have to make the following conversion:

returnValue = (T)Convert.ChangeType(sb.ToString(), typeof(T));

where T is either int or double. If I try using a dot for decimal separator in the string, for instance "2.2", Windows 7 will return double 22 but it works fine in Windows 10 (double 2.2). If I use a comma, Win7 will return what is expected but then Win 10 returns 22.

I came up with the fix above, but it kinda sucks. I'd like to know how to do it in a proper way.

makoshichi
  • 2,310
  • 6
  • 25
  • 52
  • 2
    I don't think it has anything to do with the version, but rather with regional settings. Take a look here: http://stackoverflow.com/questions/14513468/detect-decimal-separator – VuVirt Mar 24 '17 at 17:59
  • Both are English platforms, why would `CultureInfo.CurrentUICulture.NumberFormat` be any different from one another? Besides, the above code works. – makoshichi Mar 24 '17 at 18:00
  • 1
    I'll be damned! It actually works! Alright, thanks, I'll post it as a reply and give you the credits! – makoshichi Mar 24 '17 at 18:14
  • 1
    I added it as an answer myself. Thanks! – VuVirt Mar 24 '17 at 18:16

1 Answers1

3

I don't think it has anything to do with the version, but rather with regional settings. Take a look here: Detect decimal separator

Fixed:

    private void btDot_Click(object sender, EventArgs e)
    {
        char separator = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

        if (sb.ToString().Contains(separator))
            return;

        sb.Append(separator);
        tbValue.Text = sb.ToString();
    }
Community
  • 1
  • 1
VuVirt
  • 1,887
  • 11
  • 13