Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format numbers in C# so 12523 becomes "12K", 2323542 becomes "2M", etc? [duplicate]

Possible Duplicate:
Format Number like StackoverFlow (rounded to thousands with K suffix)

How can I format numbers in C# so 12523.57 becomes "12K", 2323542.32 becomes "2M", etc?

I don't know how to append the correct number abbreviation (K, M, etc) and show the appropriate digits?

So,

1000 = 1K  
2123.32 = 2K  
30040 = 30k  
2000000 = 2M  

Is there a built in way in C# to do this?

like image 726
Teradact Avatar asked Mar 09 '10 20:03

Teradact


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.

For what %D is used 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.

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.

What is %s in C?

Note: The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to print and read strings directly.


1 Answers

I don't think this is standard functionality in C#/.Net, but it's not that difficult to do this yourself. In pseudocode it would be something like this:

if (number>1000000)
   string = floor(number/1000000).ToString() + "M";
else if (number > 1000)
   string = floor(number/1000).ToString() + "K";
else
   string = number.ToString();

If you don't want to truncate, but round, use round instead of floor.

like image 94
Patrick Avatar answered Oct 19 '22 23:10

Patrick