Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format number in C# [duplicate]

Tags:

c#

Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number

How to format a number 1234567 into 1,234,567 in C#?

like image 760
Niraj Choubey Avatar asked Feb 10 '11 08:02

Niraj Choubey


People also ask

What is %s %d %F in C?

The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.

What is %d and %i in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer.

What does %3d in C mean?

%3d can be broken down as follows: % means "Print a variable here" 3 means "use at least 3 spaces to display, padding as needed" d means "The variable will be an integer"

Is double %D in C?

A double is a data type in C language that stores high-precision floating-point data or numbers in computer memory. It is called double data type because it can hold the double size of data compared to the float data type. A double has 8 bytes, which is equal to 64 bits in size.


2 Answers

For format options for Int32.ToString(), see standard format strings or custom format strings.

For example:

string s = myIntValue.ToString("#,##0");

The same format options can be use in a String.Format, as in

string s = String.Format("the number {0:#,##0}!", myIntValue);

Do note that the , in that format doesn't specify a "use a comma" but rather that the grouping character for the current culture should be used, in the culture-specific positions.

You also do not need to specify a comma for every position. The fact that there is a comma in the format string means that the culture-specific grouping is used.

So you get "1 234 567 890" for pl-PL or "1,23,45,67,890" for hi-IN.

like image 132
Hans Kesting Avatar answered Oct 10 '22 20:10

Hans Kesting


var decimalValue = 1234567m; 
var value =  String.Format("{0:N}", decimalValue); // 1,234,567.00

or without cents

var value =  String.Format("{0:N0}", decimalValue); // 1,234,567
like image 37
Andrew Orsich Avatar answered Oct 10 '22 20:10

Andrew Orsich