none
string.Format for a number RRS feed

  • Question

  • Hi,

    I need to do custom string format for a number.  the number should look like this: R12 345. It is like Number but instead of coma (,) I need to have space (" "). When I'm trying R{0:# ###} I get good values for 4 digit numbers but for 3 digit numbers i have wrong format like R 123 and I shouldn't have the leading space. I cant use CultureInfo.

    Please advice

    Tuesday, May 7, 2019 11:39 AM

Answers

  • Maybe do it in steps - format the numeric part, trim leading spaces, add the "R".

          static void Main(string[] args)
          {
             int i1 = 12345;
             int i2 = 1234;
             int i3 = 123;
    
             Console.WriteLine(Format(i1));
             Console.WriteLine(Format(i2));
             Console.WriteLine(Format(i3));
    
          }
    
          static string Format(int i)
          {
             return "R" + string.Format("{0:# ###}", i).Trim();
          }

    Output is;

    Wednesday, May 8, 2019 12:15 AM
  • SS,

    The requirements seem clear to me, although I admit it might be my misunderstanding.

    Barbi wants the number to be formatted with a space as the thousands separator, and a capital 'R' appended to the left, with no space between the 'R' and the leftmost digit. The problem is his/her solution inserts a space between the 'R' and the number if the number has fewer than 3 digits.

    I know my solution is a bit verbose, but I can't think of a way to do it using just string.Format with the restriction of not being able to use culture info.

    P.S. My first guess was that Barbi is from Malaysia or Indonesia and is trying to format currency, but a quick lookup of Wikipedia tells me the currency symbols are 'RM' and 'Rh' for the ringgit and rupiah respectively, so maybe that's not it.


    Edit: Or he/she is South African! How could I miss that? The symbol for the rand is 'R' and Seth Effricans use a space to separate thousands. I bet that's it.
    • Edited by Ante Meridian Wednesday, May 8, 2019 3:44 AM
    • Marked as answer by Barbi Rio Tuesday, May 14, 2019 7:30 AM
    Wednesday, May 8, 2019 3:39 AM

All replies

  • So you want to use a space instead of a comma for the thousands separator? If this is a cultural thing then just use the correct culture but if this is custom then use a custom NumberFormatInfo.

    var formatter = new NumberFormatInfo() { NumberGroupSeparator = " " };


    Michael Taylor http://www.michaeltaylorp3.net


    Tuesday, May 7, 2019 1:59 PM
    Moderator
  • for 3 digit numbers i have wrong format like R 123

    So what is the right format? We can guess but it is better if you tell us explicitly so we do not guess.


    Sam Hobbs
    SimpleSamples.Info

    Tuesday, May 7, 2019 7:20 PM
  • Maybe do it in steps - format the numeric part, trim leading spaces, add the "R".

          static void Main(string[] args)
          {
             int i1 = 12345;
             int i2 = 1234;
             int i3 = 123;
    
             Console.WriteLine(Format(i1));
             Console.WriteLine(Format(i2));
             Console.WriteLine(Format(i3));
    
          }
    
          static string Format(int i)
          {
             return "R" + string.Format("{0:# ###}", i).Trim();
          }

    Output is;

    Wednesday, May 8, 2019 12:15 AM
  • Note that I am waiting for clarification of requirements before making a suggestion.

    The proposed solution appears to be an unnecessary amount of code but if you prefer to do that instead of clarifying things to get alternatives then go for it.



    Sam Hobbs
    SimpleSamples.Info

    Wednesday, May 8, 2019 2:50 AM
  • So you want to use a space instead of a comma for the thousands separator? 


    My guess is that Barbi needs to format a part number or something like that. The typical rules for numbers might not apply and if so then we need to know what the rules are. The problem certainly is easily solved with many possible solutions but I want to know what the requirements are specifically.


    Sam Hobbs
    SimpleSamples.Info

    Wednesday, May 8, 2019 2:56 AM
  • SS,

    The requirements seem clear to me, although I admit it might be my misunderstanding.

    Barbi wants the number to be formatted with a space as the thousands separator, and a capital 'R' appended to the left, with no space between the 'R' and the leftmost digit. The problem is his/her solution inserts a space between the 'R' and the number if the number has fewer than 3 digits.

    I know my solution is a bit verbose, but I can't think of a way to do it using just string.Format with the restriction of not being able to use culture info.

    P.S. My first guess was that Barbi is from Malaysia or Indonesia and is trying to format currency, but a quick lookup of Wikipedia tells me the currency symbols are 'RM' and 'Rh' for the ringgit and rupiah respectively, so maybe that's not it.


    Edit: Or he/she is South African! How could I miss that? The symbol for the rand is 'R' and Seth Effricans use a space to separate thousands. I bet that's it.
    • Edited by Ante Meridian Wednesday, May 8, 2019 3:44 AM
    • Marked as answer by Barbi Rio Tuesday, May 14, 2019 7:30 AM
    Wednesday, May 8, 2019 3:39 AM
  • The requirements seem clear to me, although I admit it might be my misunderstanding.

    They are not clear because we do not know what to do for 7 digits or more, or if there can never be more than 6 digits. For the value "1234567" the format string produces "R1234 567". We do not know if the value "1234567" is possible and if it is then what the result should be.



    Sam Hobbs
    SimpleSamples.Info

    Wednesday, May 8, 2019 5:00 AM
  • Fair point.
    Wednesday, May 8, 2019 5:04 AM
  • correct format is R123 without the space between R and 123
    Wednesday, May 8, 2019 5:08 AM
  • yes for South Arica. And I cant rely on Regional Settings because I'm not sure how are they set on the client computer.

    Wednesday, May 8, 2019 5:12 AM
  • for seven digits should look like R1 234 567.
    Wednesday, May 8, 2019 5:13 AM
  • [...] I cant use CultureInfo. 


    It is not clear why you cannot use the suggested CultureInfo and the “C0” format like this:

     

    var ci = CultureInfo.GetCultureInfo( "af-za" );

    decimal amount = 12345;

    string result = string.Format( ci, "Amount is: {0:C0}.", amount ); // "Amount is: R12 345."

     

     



    • Edited by Viorel_MVP Wednesday, May 8, 2019 5:28 AM
    Wednesday, May 8, 2019 5:27 AM
  • Hi Barbi Rio,

    Thank you for posting here.

    According to your description, you could try the following code to get the string for a number.

    Code:

                string m = "R" + string.Format("{0:n0}", 12345678910).Replace(',', ' ');
                Console.WriteLine(m);

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, May 8, 2019 6:30 AM
    Moderator

  • According to your description, you could try the following code to get the string for a number.

                string m = "R" + string.Format("{0:n0}", 12345678910).Replace(',', ' ');
                Console.WriteLine(m);


    That may need some refinement, as the OP said:

    "I cant rely on Regional Settings because I'm not sure how are they set on 
    the client computer."

    For example, if the regional settings on the client computer use a period for
    the thousands separator that needs to be accommodated.

    Perhaps use the regional separator instead of a hard-coded comma in the Replace.

    - Wayne

    Wednesday, May 8, 2019 7:35 AM
  • How about this.

    class Program
    {
        static void Main ( string[] args )
        {
            var values = new[]
            {
                123,
                1234,
                12345,
                123456,
                1234567
            };
    
            var formatter = new NumberFormatInfo() { NumberGroupSeparator = " " };
            foreach (var value in values)
                Console.WriteLine(value.ToString("R#,#", formatter));
        }
    }
    Of course I would recommend that you move it into a custom formatter so you don't have to repeat this code everywhere if you need it elsewhere but the code itself is simple.

    If you want to use the current culture settings but ensure that the number separator is a space then clone the existing culture and change the format.

    var formatter = CultureInfo.CurrentCulture.NumberFormat.Clone() as NumberFormatInfo;
    formatter.NumberGroupSeparator = " ";
    
    value.ToString("R#,#", formatter);


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, May 8, 2019 1:48 PM
    Moderator
  • The following is very much like your initial attempt and many other suggestions but I hope it will work for all possibilities. I am using Int32.MaxValue as a value to format.

    Console.WriteLine('R' + string.Format("{0:# ### ### ###}", Int32.MaxValue).TrimStart());



    Sam Hobbs
    SimpleSamples.Info

    Wednesday, May 8, 2019 8:20 PM