'add commas using String.Format for number and
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.
Solution 1:[1]
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")
Solution 2:[2]
from msdn
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
Displays 1,234,567,890
Solution 3:[3]
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};
Solution 4:[4]
You can put a number after the N to specify number of decimal digits:
String.Format("{0:n0}", 0) // gives 0
Solution 5:[5]
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.
Solution 6:[6]
you just put it like this:
Console.WriteLine(**$**"Your current amount of money is: **{yourVar:c}**");
Solution 7:[7]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guffa |
| Solution 2 | pierroz |
| Solution 3 | Jhonny D. Cano -Leftware- |
| Solution 4 | TheSean |
| Solution 5 | 27k1 |
| Solution 6 | davejal |
| Solution 7 |
