ChatGPT解决这个技术问题 Extra ChatGPT

.NET String.Format() 为数字添加千位逗号

我想在数字的千位中添加一个逗号。

String.Format() 是正确的路径吗?我会使用什么格式?


A
AustinWBryan
String.Format("{0:n}", 1234);  // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876

如何复制“N”说明符,但小数位数与数字中的一样多?
@Justin:根据msdn.microsoft.com/en-us/library/0c899ak8.aspx,“,”(和“。”)被正确的本地化字符替换。
如果您想在您的页面上强制使用系统定义格式以外的十进制格式,您可以更改 CurrentCulture,如下例所示:var nlBE = new System.Globalization.CultureInfo("nl-BE"); nlBE.NumberFormat.CurrencyDecimalDigits = 2; nlBE.NumberFormat.CurrencyDecimalSeparator = ","; nlBE.NumberFormat.CurrencyGroupSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = nlBE;
@VVVV - 那么你可能传递的是 string 而不是 number。如果你有一个字符串,你需要先转换为浮点数或双精度数。试试string.Format("{0:n0}", Double.Parse(yourValue));
为了复制 n 说明符的行为,但数字本身中存在尽可能多的十进制数字,我不得不使用这个格式字符串而不是 #,##0.## (来自另一个答案)
J
Jon Schneider

我发现这是最简单的方法:

myInteger.ToString("N0")

您也可以将它与 string.Format 一起使用,如 string.Format("这里是一些带逗号的数字,没有小数点,{0:N0}", 123456789(;
不应该是 myInteger.ToString("N0") ... string.tostring 我认为不会起作用。
我知道现在已经5年了,但是谢谢!它适用于 > 4 个字符和 < 4 个字符的数字。
@AskYous - 好吧,它也适用于 4 个字符。不妨说它适用于任何长度。
这是有效的,但它正在改变区域设置
p
p.campbell
int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

从国际化的角度来看,这种解决方案并不好 - 其他文化使用 , 以外的字符作为千位分隔符,例如空格甚至 .
工作感谢 + 1。已扩展,因此最多显示 2 dp number.ToString("#,##0.##")
@MacSigler 实际上不是这样,请参阅 Roger Lipscombe 对上述答案的评论: String.Format 将自动应用本地化。
@MacSigler 就是这样,这段代码 总是打印出逗号。仅当文化是一种期望逗号的文化(例如 en-US 或不变)。如果该区域性需要另一个分隔符(例如 .),.NET 将自动将逗号替换为该分隔符。如果您仍然不明白为什么会这样,我再次敦促您阅读 Roger 发布的链接。
@MacSigler Justin 的评论仍然正确,因为如果您没有明确强制文化为 en-US,它将从本地机器继承文化设置。我的理解是编译上面的代码,然后在具有不同文化(具有不同数字分隔符)的两台机器上运行它会产生不同的结果。如果您希望它始终产生逗号,则需要明确设置使用逗号的文化(例如不变量)。
p
pudi kalicharan

如果你想要特定的文化,你可能想试试这个:

使用命名空间:“使用 System.Globalization;”

(19950000.0).ToString("N",new CultureInfo("en-US")) = 19,950,000.00

(19950000.0).ToString("N",new CultureInfo("is-IS")) = 19.950.000,00

印度文化:(19950000.0).ToString("N",new CultureInfo("hi-IN"))= 1,99,50,000.00

注意:有些文化使用 , 来表示十进制而不是 .,所以要小心。


答对了! (和“N0”隐藏小数)
C
CoderTao

标准格式及其相关输出,

Console.WriteLine("Standard Numeric Format Specifiers");
String s = String.Format("(C) Currency: . . . . . . . . {0:C}\n" +
                    "(D) Decimal:. . . . . . . . . {0:D}\n" +
                    "(E) Scientific: . . . . . . . {1:E}\n" +
                    "(F) Fixed point:. . . . . . . {1:F}\n" +
                    "(G) General:. . . . . . . . . {0:G}\n" +
                    "    (default):. . . . . . . . {0} (default = 'G')\n" +
                    "(N) Number: . . . . . . . . . {0:N}\n" +
                    "(P) Percent:. . . . . . . . . {1:P}\n" +
                    "(R) Round-trip: . . . . . . . {1:R}\n" +
                    "(X) Hexadecimal:. . . . . . . {0:X}\n",
                    - 1234, -1234.565F);
Console.WriteLine(s);

示例输出(en-us 文化):

(C) Currency: . . . . . . . . ($1,234.00)
(D) Decimal:. . . . . . . . . -1234
(E) Scientific: . . . . . . . -1.234565E+003
(F) Fixed point:. . . . . . . -1234.57
(G) General:. . . . . . . . . -1234
    (default):. . . . . . . . -1234 (default = 'G')
(N) Number: . . . . . . . . . -1,234.00
(P) Percent:. . . . . . . . . -123,456.50 %
(R) Round-trip: . . . . . . . -1234.565
(X) Hexadecimal:. . . . . . . FFFFFB2E

这个答案包含了很多有用的信息。通过示例学习我现在看到了字符串格式中 0 和 1 的含义。
哇,很好的解释
D
Dennis

这是最好的格式。适用于所有这些情况:

String.Format( "{0:#,##0.##}", 0 ); // 0
String.Format( "{0:#,##0.##}", 0.5 ); // 0.5 - some of the formats above fail here. 
String.Format( "{0:#,##0.##}", 12314 ); // 12,314
String.Format( "{0:#,##0.##}", 12314.23123 ); // 12,314.23
String.Format( "{0:#,##0.##}", 12314.2 ); // 12,314.2
String.Format( "{0:#,##0.##}", 1231412314.2 ); // 1,231,412,314.2

如果我想要点作为千位分隔符和逗号作为小数分隔符怎么办?
赞成,因为它不显示 12,314.0(如 n1 格式)但 12,314 :)
v
von v.

投票最多的答案非常好,并且已经帮助了大约 7 年。随着 C# 6.0 的引入,特别是字符串插值的引入,有一种更简洁且 IMO 更安全的方法来执行所要求的to add commas in thousands place for a number

var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal

其中变量 i 代替占位符(即 {0})。所以没有必要记住哪个物体去哪个位置。格式(即:n)没有改变。如需了解新功能的完整功能,您可以go to this page


a
amdev

就这么简单:

float num = 23658; // for example 
num = num.ToString("N0"); // Returns 23,658

更多信息在 Here


D
Dan
String.Format("{0:#,###,###.##}", MyNumber)

这将在相关点给你逗号。


":n" 方法更好,因为它应该尊重用户的语言环境。
这是真的,但不能保证在千位给你逗号,因为它尊重用户的语言环境。
回到你身边:这是真的,但不能保证尊重用户的语言环境,因为它使用逗号作为千位分隔符。 (例如,在葡萄牙,逗号是小数点分隔符。)
如果要在 .您需要将 # 替换为 0。 msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx:如果存在 1,则零用相应的数字替换零;否则,结果字符串中将出现零,而如果存在一,则将“#”符号替换为相应的数字;否则,结果字符串中不会出现数字。
此方法可以满足我的要求,有关 Int32.ToString 方法的 msdn 页面将成为使用它的主要位置 msdn.microsoft.com/en-us/library/8wch342y.aspx 对于此特定应用程序也不是很有帮助
Y
Yitzhak Weinberg

以下示例显示了使用包含零占位符的自定义格式字符串格式化的几个值。

String.Format("{0:N1}", 29255.0);

或者

29255.0.ToString("N1")

结果“29,255.0”

String.Format("{0:N2}", 29255.0);

或者

29255.0.ToString("N2")

结果“29,255.00”


很好的答案,但是 29.255,00 呢?
@Roxy'Pro 更改语言环境/文化?
@MaartenBodewes 我认为有相应的字母,例如“N1”,“F1”或类似的东西=)但是改变文化肯定会起作用..
R
Ravi Desai

如果您希望强制使用“,”分隔符而不考虑文化(例如在跟踪或日志消息中),以下代码将起作用,并且具有告诉下一个偶然发现它的人您正在做什么的额外好处。

int integerValue = 19400320; 
string formatted = string.Format(CultureInfo.InvariantCulture, "{0:N0}", integerValue);

设置为“19,400,320”


M
Mark Z.

C# 7.1(可能更早?)通过字符串插值使这变得简单而美观:

var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";

哇,这真的很整洁,不知道c#有,谢谢!
实际上它是/曾经是 7.0,请参阅:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
b
brakeroo

更简单,使用字符串插值而不是 String.Format

 $"{12456:n0}"; // 12,456
 $"{12456:n2}"; // 12,456.00

或使用你的变量

 double yourVariable = 12456.0;
 $"{yourVariable:n0}"; 
 $"{yourVariable:n2}"; 

p
p.campbell
int num = 98765432;
Console.WriteLine(string.Format("{0:#,#}", num));

或 Console.WriteLine("{0:#,#}",num);如果您只想打印它。但我猜 string.Format(...) 更有用。
c
cmujica

例如 String.Format("{0:0,0}", 1); 返回 01,对我来说无效

这对我有用

19950000.ToString("#,#", CultureInfo.InvariantCulture));

输出 19,950,000


但是如果我们将 19950000 值放入变量中并像这样 var test = "19950000"; test.ToString("#,#", CultureInfo.InvariantCulture));它不工作
佚名

请注意,您要格式化的值应该是数字。看起来它不会采用数字的字符串表示形式,格式是逗号。


A
Abolfazl Rastgou
String.Format("0,###.###"); also works with decimal places

d
dunwan

您可以使用这样的函数来格式化数字并可选择传入所需的小数位。如果未指定小数位,它将使用两位小数。

    public static string formatNumber(decimal valueIn=0, int decimalPlaces=2)
    {
        return string.Format("{0:n" + decimalPlaces.ToString() + "}", valueIn);
    }

我使用十进制,但您可以将类型更改为任何其他类型或使用匿名对象。您还可以添加对负小数位值的错误检查。


b
belal ahmad

您想要相同的格式值和特定的文化。

 Double value= 1234567;
 value.ToString("#,#.##", CultureInfo.CreateSpecificCulture("hi-IN"));

输出:12,34,567


这是印度文化特有的,最好使用更通用的答案。
Y
Yusuff Sodiq

我尝试了上面的许多建议,但以下对我来说效果更好:

string.Format("{0:##,###.00}", myValue)

但是当你有像 0.2014 这样的值时它会失败,它给出 .21 为此我使用

string.Format("{0:#,##0.00}", myValue)

S
Sepideh I

尝试这个:

var number = 123456789;
var str = number.ToString("N0");

结果是:“123,456,789”


A
Ali

如果你想在 DataGridview 中显示它,你应该改变它的类型,因为默认是 String 并且因为你把它改成小数,所以它被认为是带浮点数的数字

Dim dt As DataTable = New DataTable
dt.Columns.Add("col1", GetType(Decimal))
dt.Rows.Add(1)
dt.Rows.Add(10)
dt.Rows.Add(2)

DataGridView1.DataSource = dt

8
8 John Volante

我过去不再担心文化和潜在格式问题的方法是,我将其格式化为货币,然后取出货币符号。

if (decimal.TryParse(tblCell, out result))

{
  formattedValue = result.ToString("C").Substring(1);
}

此代码不是独立于文化的——它将使用运行代码的机器上设置的任何默认文化。这可能会产生不希望的输出,其中该文化将其货币符号放在数字的末尾而不是开头(例如 fr-FR),或者使用多个字符来表示货币(例如 da-DK),或者不分隔使用逗号的数千人(例如欧洲大陆的大部分地区)。