I have a number of say 12865 I need to translate it to 12,865 . Ie if the number is more than a thousand, convert it to this format, but if the number is less than a thousand, then leave it as it is.
- 2The number is a number, and what you say is the format of converting a number into a string, look here or here . - tym32167
|
2 answers
Microsoft Docs: Standard Numeric Format Strings
N "or" n "
Result: Integral and decimal digits, group separators with optional negative sign.
1234.567 ("N", en-US) -> 1,234.57
1234.567 ("N", en-RU) -> 1 234.57
1234 ("N1", en-US) -> 1.234.0
1234 ("N1", en-RU) -> 1 234.0
-1234.56 ("N3", en-US) -> -1,234.560
-1234.56 ("N3", ru-RU) -> -1 234,560
Accordingly, for your case (separation of digits by commas) the code will be as follows:
int number = 123456789; string formattedNumber = number.ToString("N0", CultureInfo.CreateSpecificCulture("en-US")); Result:
123,456,789 |
string ToStringWithSeparator(int num, string separator) { return Enumerable.Range(0, 10) .Select(x => new string(num.ToString() .Reverse() .Skip(x * 3) .Take(3) .Reverse() .ToArray())) .Reverse() .SkipWhile(x => string.IsNullOrEmpty(x)) .Reverse() .Aggregate(string.Empty, (x, a) => $"{a}{separator}{x}"); } |