Double.Parse 用于本机语言支持

发布于 2024-12-11 07:29:47 字数 189 浏览 0 评论 0原文

我有一个德语值 20,55
当我将区域设置更改为美国时,运行此代码后该值显示为 2055.0

double d = Double.Parse("20,55",CultureInfo.CurrentCUCulture);

这是为什么?

I have a value 20,55 which is in German language.
When I change the regional settings to US the value gets displayed as 2055.0 after running this code:

double d = Double.Parse("20,55",CultureInfo.CurrentCUCulture);

Why is that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天冷不及心凉 2024-12-18 07:29:47

因为在美国 , 是千位分隔符并且被忽略了?就像在德国(和欧洲大陆)中 . 是千位分隔符一样,它会被忽略吗?

在德国你写:1.000,55。在美国,您可以写:1,000.55(如果前面有一个数字,有些思想流派会删除 ,。所以 1000.55 和 11,000.55)。

现在,如果您想确保您的程序使用 de-DE 文化,请在各处作为参数传递

CurrentCulture culture = new CultureInfo("de-DE");

double d = double.Parse("20,55", culture);

Because in US the , is the thousand separator and it's ignored? In the same way that in Germany (and continental Europe) the . is the thousand separator and it's ignored?

In Germany you write: 1.000,55. In USA you write: 1,000.55 (and there are some schools of thought that remove the , if there is a single digit before. So 1000.55 and 11,000.55).

Now, if you want to be sure your program is using the de-DE culture, pass as a parameter everywhere

CurrentCulture culture = new CultureInfo("de-DE");

double d = double.Parse("20,55", culture);
咋地 2024-12-18 07:29:47

在美国,小数点分隔符是 .,而不是 ,。如果您尝试解析 20,55,它(显然)会忽略逗号作为标准三元组分隔符(例如 1,234,567.89),即使没有三位数字在所有这些中。

如果要解析欧洲风格的数字,则需要使用欧洲风格的文化设置来解析它。

In the US, the decimal separator is ., not ,. If you attempt to parse 20,55, it will (apparently) ignore the commas as standard triplet separators (such as in 1,234,567.89), even though there aren't three digits in all of them.

If you want to parse a Euro-style number, you need to parse it with a Euro-style culture setting.

百合的盛世恋 2024-12-18 07:29:47

这是因为美国十进制分隔符是 . 而不是 ,

如果您想避免该问题,无论用户的区域设置如何,您都可以编写一个扩展方法:

public static String ToRegionalNumber(this String str) {
    String regionalNb = str.Replace(",", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
    regionalNb = regionalNb .Replace(".", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
    return regionalNb ;
}

并在使用您的号码时调用此方法:

double d = Double.Parse("20,55".ToRegionalNumber());

It's because the US decimal separator is the . and not the ,.

If you want to avoid that problem no matter the regional settings of the user, you could write a extension method:

public static String ToRegionalNumber(this String str) {
    String regionalNb = str.Replace(",", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
    regionalNb = regionalNb .Replace(".", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
    return regionalNb ;
}

And call this method when working with your number:

double d = Double.Parse("20,55".ToRegionalNumber());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文