[英]How can I detect the Windows version for solving ',' or '.' problems when converting string to double?
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. 我必须使用Windows窗体在C#中制作一个数字键盘,该窗体可以接受并验证
double
和int
值,但是用于double
的string
格式在Windows 7和10之间有所不同。这是我可以测试的唯一操作系统,我想出了一个过于严格的解决方案。 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
. 其中
T
是int
或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). 如果我尝试在字符串中使用点作为小数点分隔符,例如“ 2.2”,则Windows 7将返回
double
22,但在Windows 10( double
2.2)中运行良好。 If I use a comma , Win7 will return what is expected but then Win 10 returns 22. 如果我使用逗号 ,则Win7将返回预期值,但Win 10将返回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.
我想知道如何正确地做。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.