Using String.Format how can i ensure all numbers have commas after every 3 digits eg 23000 = "23,000" and that 0 returns "0".
String.Format("{0:n}", 0); //gives 0.00 which i dont want. I dont want any decimal places, all numbers will be integers.
Using String.Format how can i ensure all numbers have commas after every 3 digits eg 23000 = "23,000" and that 0 returns "0".
String.Format("{0:n}", 0); //gives 0.00 which i dont want. I dont want any decimal places, all numbers will be integers.
You can do this, which I find a bit cleaner to read the intent of:
String.Format("{0:#,###0}", 0);
Example:
string.Format("{0:#,###0}", 123456789); // 123,456,789
string.Format("{0:#,###0}", 0); // 0
If your current culture seting uses commas as thousands separator, you can just format it as a number with zero decimals:
String.Format("{0:N0}", 0)
Or:
0.ToString("N0")
from msdn
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
Displays 1,234,567,890
You can also play around a little with the CultureInfo object, if none of the other solutions work well for you:
var x = CultureInfo.CurrentCulture;
x.NumberFormat.NumberDecimalSeparator = ",";
x.NumberFormat.NumberDecimalDigits = 0;
x.NumberFormat.NumberGroupSizes = new int[] {3};
You can put a number after the N to specify number of decimal digits:
String.Format("{0:n0}", 0) // gives 0
I up-marked another answer and then found that zero values are an empty string.
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("de-DE");
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
double x = 23232323.21;
string y = x.ToString("#,0", System.Globalization.CultureInfo.CurrentCulture);
The string is returned in the current culture which is German therefore y = 23.232.323
y = 0 when x = 0.
relatively american number to ordinal.
using static System.Threading.Thread;
public static string NumberToOrdinal(int number, CultureInfo? culture = null)
{
var numberString = number.ToString(
format: "#,0",
provider: culture ?? CurrentThread.CurrentCulture);
// Examine the last 2 digits.
var lastDigits = number % 100;
// If the last digits are 11, 12, or 13, use th. Otherwise:
if (lastDigits is >= 11 and <= 13) return $"{numberString}th";
// Check the last digit.
return (lastDigits % 10) switch
{
1 => $"{numberString}st",
2 => $"{numberString}nd",
3 => $"{numberString}rd",
_ => $"{numberString}th",
};
}
ps i never comment on these things because stack overflow won't let me and sometimes its not worth upstaging everyone with a new answer for a slight improvement. Screw stackoverflow. I've been here for years and still can't comment- which is why i still don't post.