Format a number to display a comma when larger than a thousand

倾然丶 夕夏残阳落幕 提交于 2019-11-30 23:51:24

问题


I am writing some code in Visual Basic.net and have a question.

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?

For e.g.

1234 will be stored as 1,234 12345 will be stored as 12,345 123456 will be stored as 123,456

Is this done with a TryParse statement?

May I have some help to so this?


回答1:


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.




回答2:


For those wanting to do a currency with commas and decimals use the following: .ToString("$0,00.00")




回答3:


Using $ notation:

int myvar = 12345;    
Console.WriteLine($"Here is my number: {myvar:N0}");


来源:https://stackoverflow.com/questions/19999560/format-a-number-to-display-a-comma-when-larger-than-a-thousand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!