.net ToString("0") 与 ToString(CultureInfo.InvariantCulture)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1487532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ToString("0") versus ToString(CultureInfo.InvariantCulture)
提问by Jan Zich
I would like to make sure that certain numbers in my application are printed without any separators, groupings etc. no matter what the current environment is. It seems that the following two methods produce the same results (there are possibly more):
我想确保我的应用程序中的某些数字在打印时没有任何分隔符、分组等,无论当前环境如何。似乎以下两种方法产生了相同的结果(可能还有更多):
123456789.ToString("0");
123456789.ToString(CultureInfo.InvariantCulture);
Are you aware of any edge cases or quirks? Which one is more "correct"? Which one would you use?
你知道任何边缘情况或怪癖吗?哪个更“正确”?你会用哪一种?
I used to use the second one, but recently I found the first one and started using it because it does not require the additional using System.Globalization.
我曾经使用第二个,但最近我找到了第一个并开始使用它,因为它不需要额外的using System.Globalization.
回答by Jan Zich
Based on the answers and the discussion here, I did some more investigation. Here is what I found:
根据这里的答案和讨论,我做了更多调查。这是我发现的:
When you use
12345678.ToString()without any arguments, .NET uses general the general format specifier "G"which is affected only by NumberFormatInfo.NegativeSign, NumberFormatInfo. NumberDecimalSeparator, NumberFormatInfo.NumberDecimalDigits and NumberFormatInfo.PositiveSign. To me this says that in any culture12345678.ToString()should always produce "12345678".If you want to separate digits, you need to use the numeric format specifier "N"(or, of course, to provide a custom format string). The digit grouping also applies to "C" and "P".
The invariant culture doesindeed specify digit grouping(by 3 digits, of course) and a digit separator. So the reason that
123456789.ToString(CultureInfo.InvariantCulture)produces "123456789" is not because of the invariant culture, but it's because of the default general numeric format specifier "G".
当您
12345678.ToString()不带任何参数使用时,.NET 使用一般通用格式说明符“G”,该说明符仅受 NumberFormatInfo.NegativeSign、NumberFormatInfo 影响。NumberDecimalSeparator、NumberFormatInfo.NumberDecimalDigits 和 NumberFormatInfo.PositiveSign。对我来说,这表示在任何文化中12345678.ToString()都应该始终产生“12345678”。如果要分隔数字,则需要使用数字格式说明符“N”(当然,也可以提供自定义格式字符串)。数字分组也适用于“C”和“P”。
该固定区域性不确实指定数字分组(由3个数字,当然)和数字分隔。所以
123456789.ToString(CultureInfo.InvariantCulture)产生“123456789”的原因不是因为不变的文化,而是因为默认的通用数字格式说明符“G”。
So I would say that the conclusion is that it's perfectly OK not to worryabout any extra arguments and just use:
所以我会说结论是完全可以不用担心任何额外的参数,只需使用:
12345678.ToString()
I think that this the best from all cases because it means that usually you don't need to even call ToString()because most of the print/write functions accept all sorts of arguments and do the ToString()for you.
我认为这是所有情况下最好的,因为这意味着通常您甚至不需要调用,ToString()因为大多数打印/写入函数都接受各种参数并ToString()为您完成。
回答by Hans Ke?ing
The two methods are not equivalent: the first is using the CurrentCulture. This could lead to extra dots/commas in certain cultures (I don't have examples).
这两种方法并不等效:第一种是使用CurrentCulture. 这可能会导致在某些文化中出现额外的点/逗号(我没有例子)。
When you use InvariantCultureyou are certain that always the same formatting is used.
当您使用时,InvariantCulture您可以确定始终使用相同的格式。
Edit: And, if you use CodeAnalysis, that will complain when you don't use a CultureInfo.
编辑:而且,如果您使用CodeAnalysis,那么当您不使用CultureInfo.
回答by Bobby
As I see it, The first one will format is a number with at least one character using the default culture of the computer. The second will format it as a number depending on the InvariantCulture rules.
正如我所见,第一个将使用计算机的默认文化格式化一个至少有一个字符的数字。第二个将根据 InvariantCulture 规则将其格式化为数字。
Bobby
鲍比
回答by XenoPuTtSs
(~5 years later...)
(~5年后...)
I was looking up this exact question, but since there was no accepted answer and even though Jan Zich is correct I thought I would put together a little example to test this.
我正在查找这个确切的问题,但是由于没有公认的答案,即使 Jan Zich 是正确的,我想我还是会整理一个小例子来测试这个。
I would also go so far to say that there is no difference between .ToString(), .ToString("0"), and .ToString(Any Culture Info) (as far as integers and decimals are concerned)
我还想说 .ToString()、.ToString("0") 和 .ToString(Any Culture Info) 之间没有区别(就整数和小数而言)
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures)
.Except(CultureInfo.GetCultures(CultureTypes.SpecificCultures));
foreach(var c in cultures){
var num = (int.MinValue);/*
var num = (int.MaxValue);/*
var num = (decimal.MinValue);/*
var num = (decimal.MaxValue);/*
--*/
var s1 = num.ToString("0") ;
var s2 = num.ToString(c);
if(s1 != s2){
var s = string.Format("{2}: {0} {1}",s1,s2,c);
s.Dump();
}
}
回答by Vlad Rudenko
The .ToString()and .ToString(CultureInfo.InvariantCulture)always give the same result for integers.
该的ToString()和的ToString(CultureInfo.InvariantCulture)总是给出整数相同的结果。
The code below gives "809 cultures tested, 0 differences found" result on my PC:
下面的代码在我的 PC 上给出了“ 809 种文化测试,发现 0 种差异”的结果:
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures).ToArray();
var numbers = new[] { 0, -1, 1, int.MinValue, int.MaxValue };
var diffsFound = 0;
foreach (var culture in cultures)
{
foreach (var number in numbers)
{
var s1 = number.ToString();
var s2 = number.ToString(culture);
if (s1 != s2)
{
Console.WriteLine($"{culture.DisplayName}: {s1} != {s2}");
diffsFound++;
}
}
}
Console.WriteLine($"{cultures.Length} cultures tested, {diffsFound} differences found.");
回答by Gokce Mutlu
2 lines do different things. The first line formats the number with the local culture and the second one converts it to string without formatting but using CultureInfo.InvariantCulture.
2 行做不同的事情。第一行使用本地文化格式化数字,第二行将其转换为字符串而不格式化,但使用 CultureInfo.InvariantCulture。
You use CultureInfo.InvariantCulture with this kind of methods (ToString, ToLower ...) to make sure that when the value is used by any software (database, another library ...), no matter what their culture is, it will result the same value and when they can pick up this value, they can continue processing it. However if you don't use this the other software has to figure out what your culture is. Did you mean decimal separator with comma or something else ... ?
您将 CultureInfo.InvariantCulture 与这种方法(ToString、ToLower ...)一起使用,以确保当任何软件(数据库、另一个库 ...)使用该值时,无论它们的文化是什么,都会导致相同的值,当他们可以选择这个值时,他们可以继续处理它。但是,如果您不使用它,其他软件必须弄清楚您的文化是什么。你的意思是用逗号或其他东西的小数点分隔符......?
All and all use CultureInfo.InvariantCulture when you want to exchange/use values among libraries, databases and use CultureInfo.CurrentCulture to show to the users of your application.
当您想在库、数据库之间交换/使用值并使用 CultureInfo.CurrentCulture 向应用程序的用户显示时,所有和所有的人都使用 CultureInfo.InvariantCulture。
// for softwares
string mystring1 = 1234.ToString("0", CultureInfo.InvariantCulture);
// for your application users
string mystring2 = 1234.ToString("0", CultureInfo.CurrentCulture);
回答by Nicolas Webb
If you're wanting to make sure to specify "no formatting, no matter what" I personally think the first option you have:
如果您想确保指定“无格式,无论如何”,我个人认为您拥有的第一个选项是:
123456789.ToString("0");
better communicates the intent. The downside would be if a culture overrode the format string of "0" for the numeric type you are using.
更好地传达意图。不利的一面是,如果文化覆盖了您正在使用的数字类型的格式字符串“0”。

