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.