I would like to format values so that a value like 20000 would display as $20k and so on. What would be the C# format?
Asked
Active
Viewed 3,650 times
4
-
How are you going to display 1, 10, 999, 1000, 20100, 1000000? There are plenty of cases that you should specify for the question to be precisely answerable. – Mehrdad Afshari Jun 15 '10 at 16:27
-
I think you need to give some more details. How would it display 20001? What about 500? Or 2020000? Are you basically rounding to thousands, millions, billions and displaying the number with a letter after it? – bwarner Jun 15 '10 at 16:27
-
1C# doesn't _have_ formats. I presume you're asking about .NET? – John Saunders Jun 15 '10 at 16:30
-
To keep it simple, numbers above 999 and whole 1000's show that format. – Tony_Henrich Jun 15 '10 at 16:49
4 Answers
7
double amount = 20000;
string formatted = string.Format("${0:0,.0}K", amount);

Andrew
- 91
- 1
- 3
-
-
[Documentation for using `,` like that](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierTh) – sirbrialliance Nov 30 '22 at 19:49
4
I think you need to write your own function to divide by 1,000
var culture = CultureInfo.GetCultureInfo("en-US");
int amount = 20000 / 1000;
var amountString = string.Format(culture, "{0:C}K", amount);
Console.WriteLine(amountString); // $20.00

abatishchev
- 98,240
- 88
- 296
- 433

simendsjo
- 4,739
- 2
- 25
- 53
2
I'm trying to do a similar thing, but cannot use the ToString("format") syntax in my case. This might help others though:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierTh
double value = 1234567890;
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235
For millions...thousands would be something like...
Console.WriteLine(value.ToString("#,##0,", CultureInfo.InvariantCulture));

roadsunknown
- 3,190
- 6
- 30
- 36
1
static void Main(string[] args)
{
int val = 20000;
string currency = string.Format("Total: {0}",ToKdisplay (val));
}
private static string ToKdisplay(int val)
{
string result = "";
result = val > 1000 ? string.Format("${0}K", val / 1000) : string.Format("${0}", val);
return result;
}

Waleed A.K.
- 1,596
- 13
- 13