string 格式化数字以在大于一千时显示逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19999560/
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
Format a number to display a comma when larger than a thousand
提问by Simon
I am writing some code in Visual Basic.net and have a question.
我正在 Visual Basic.net 中编写一些代码并有一个问题。
If I have a long number, that is larger than 1000, how can I format this value to be 1,000 (with a comma) and for this to be stored in a string?
如果我有一个大于 1000 的长数字,如何将此值格式化为 1,000(带逗号)并将其存储在字符串中?
For e.g.
例如
1234 will be stored as 1,234 12345 will be stored as 12,345 123456 will be stored as 123,456
1234 将存储为 1,234 12345 将存储为 12,345 123456 将存储为 123,456
Is this done with a TryParse statement?
这是通过 TryParse 语句完成的吗?
May I have some help to so this?
我可以帮忙吗?
回答by Ric
Take a look at The Numeric ("N") Format Specifier
General use:
一般使用:
Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
If you are only using integers then the following:
如果您只使用整数,则以下内容:
Dim numberString As String = 1234.ToString("N0")
Will show numberString = "1,234"
as the "N0"
format will not add any figures after a decimal point.
将显示numberString = "1,234"
为"N0"
格式不会在小数点后添加任何数字。
回答by Exile Studios
For those wanting to do a currency with commas and decimals use the following: .ToString("$0,00.00")
对于那些想要用逗号和小数做货币的人,请使用以下内容: .ToString("$0,00.00")
回答by Denis
Using $
notation:
使用$
符号:
int myvar = 12345;
Console.WriteLine($"Here is my number: {myvar:N0}");