There is a need to display large numbers on the screen, but this must be done so that the user can easily perceive this number, that is, add a separator between every 3 digits in the number. For example: (6485251 -> "6.485.251") .

How can you implement a method that will accept, let's say a variable of type "int" and return a "string" with delimiters?

4 answers 4

String.Format("{0:n}", 6485251 ); //вывод: 6,485,251.00 string.Format("{0:n0}", 6485251); //вывод: 6.485.251 
      int f = 1234567; string s = f.ToString("N3"); 

    In this format, digits will be separated by spaces.

    • eight
      Rather, digits will be separated by the symbol set in the current culture. - Alexander Petrov

    Give Linq Monster! (there is nothing to say about the effectiveness of the algorithms, it is beautiful))

     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.IsNullOrWhiteSpace(x)) .Reverse() .Aggregate(string.Empty, (x, a) => $"{a}{separator}{x}"); } 

    How to check

     Console.WriteLine(ToStringWithSeparator(6485251, " ")); 

    Conclusion

     6 485 251 
    • not only "IsNullOrWhiteSpace", but "IsNullOrEmpty", and so thanks - TheFrankyDoll
    • 2
      @TheFrankyDoll well, this is more a joke answer, and in this case it doesn't make any difference what to use, it will work equally slowly :) - tym32167

    You can write your method of separating integers by digits, like this.

      static string Separate(int number) { var strList = new List<string>(); while (number != 0) { var t = number % 1000; number /= 1000; strList.Add(t.ToString()); } strList.Reverse(); // Разделитель задайте сами var preparedNumber = String.Join(" ", strList.ToArray()); return preparedNumber; } 
    • If you use Stack , you don’t have to do reverse, and if you use StringBuilder instead of string concatenation, the algorithm will decrease from quadratic to linear :) Well, it's just if you are interested in improving your function. - tym32167
    • @ tym32167 And where is the quadratic time? - Philippe
    • @Philippe here String.Join(" ", strList.ToArray()); - the string concatenation in this variant is quadratic - tym32167
    • @Philippe checked source files , I'm sorry, I was wrong, still linear :) - tym32167
    • @ tym32167 Fuh, but something I was scared) - Philippe