Jordan Foreman
Jordan Foreman

Reputation: 3888

C# Formatting Long variable as String

I'm trying to take a variable (long), and convert it to a string, such that:

150 -> 150
1500 -> 1,500
1234567 -> 1,234,567

I know this shouldn't be difficult, but so far, I've only been able to find two different solutions, and they're not giving me the output I want:

This: String.Format("{0:n}", *long variable*.ToString())

gives me: 2000 -> 2000

and this: *long variable*.ToString("N" or "N0")

gives me: 2000 -> 2000.00

Upvotes: 8

Views: 19854

Answers (4)

a553
a553

Reputation: 499

Console.WriteLine("{0:0,0}", 1500L); // Writes '1,500' (exact output depends on culture)

Upvotes: 0

Paulus E Kurniawan
Paulus E Kurniawan

Reputation: 754

This should give the formatting you want:

String.Format("{0:n0}", number);

Upvotes: 0

Marc
Marc

Reputation: 9354

Either of these work fine

string.Format("{0:n0}", someNumber);

string.Format("{0:#,##0}", someNumber);


These can be used with ToString() as well, (e.g. someNumber.ToString("n0");)

Upvotes: 3

Jordan Foreman
Jordan Foreman

Reputation: 3888

Someone commented the correct syntax on an answer that was deleted, so for the sake of anyone reading this in the future, here is what works:

String.Format("{0:#,##0}", *long variable*)

Upvotes: 9

Related Questions