Simple C# stringformatting question

Andrew Charlton 96 Reputation points
2021-01-21T11:21:26.933+00:00

I have a case where I need to be able to convert a float to a string using a formatter that will not be known until runtime. I thought that this would be simple. However, I am having problems coming up with the correct format string for fixed width, right justified padded on left with spaces. Here is a stripped down simplified demonstration of my problem:

namespace ConsoleApp
{

  class Program
  {
    public static void FormatHandler( string Formatter, float Value)
    {
      // Simple stripped down functionality for now; format the value
      // accoring to Formatter and print.
      string OutputStr = Value.ToString( Formatter ) ;
      Console.WriteLine(OutputStr);
    }


    static void Main(string[] args)
    {
      // Test the format handler method (in real life the formatter could be
      // runtime dependent, e.g. it could come from a database or configuration
      // file or other).
      float Val = 23.592f ;

      FormatHandler( "F", Val ) ;   // Simple case, default float conversion.
      FormatHandler( "F1", Val ) ;  // Only one decimal place please.


      // How do I do fixed width, padding with space if necessary on the left?
      // For example, I want the resultant string to be five characters wide and
      // one D.P. " 23.5". Here are my attempts...


      // Nope print "5:F1" not " 23.5".
      FormatHandler( "5:F1", Val ) ;

      // Nope. Better, but padded with leading zeros not spaces.
      FormatHandler ( "000.0", Val ) ;

      // Nope. You would have thought, but looks the same as "F1"
      FormatHandler ( "###.#", Val ) ;

      // There must be a way?
    }

  }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,356 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andrew Charlton 96 Reputation points
    2021-01-21T12:56:58.847+00:00

    Hello @Viorel ,

    Thank you so much for spending the time to help me. The solution you offer can be made to work, but then does require an extra parameter. I have been trying to work out ways that do not need an extra width parameter, and just use the Formatter parameter. I have been battling with the C# formatters, and unless I have misunderstood things, it seems that they behave differently in different situations. (Nothing beats the good old C language "printf" formatters; consistent and you could always get exactly what you wanted :-) ).

    So here is the solution I am going with. It has the disadvantage of being clunky, I have to change the simple formatters (from "F" to "0:F" etc), and it does not work with all formats. Rather unsatisfactory, but for what I am doing sufficient:

    namespace ConsoleApp  
    {  
      
      class Program  
      {  
        public static void FormatHandler( string Formatter, float Value)  
        {  
          string TmpStr = "{0," + Formatter + "}" ;  
          string OutputStr = string.Format( TmpStr, Value ) ;  
          Console.WriteLine(OutputStr);  
        }  
      
      
      
        static void Main(string[] args)  
        {  
          // Test the format handler method (in real life the formatter could be  
          // runtime dependent, e.g. it could come from a database or configuration  
          // file).  
          float Val = 23.592f ;  
      
          FormatHandler( "0:F", Val ) ;   // Simple case, default float conversion.  
          FormatHandler( "0:F1", Val ) ;  // Only one decimal place please.  
      
      
          // How do I do fixed width, padding with space if necessary on the left?  
          // For example, I want the resultant string to be five characters wide and  
          // one D.P. " 23.5". Here are my attempts...  
          FormatHandler( "5:F1", Val ) ;  
      
        }  
      
      }  
    }  
    

    Once again, thank you for your time.


1 additional answer

Sort by: Most helpful
  1. Viorel 112.9K Reputation points
    2021-01-21T11:49:14.187+00:00

    Check an example:

    string s = string.Format( "{0,5:F1}", Val );
    

    You can write a FormatHandler that accepts “5:F1” as parameter and uses string.Format.

    Or you can do this:

    public static void FormatHandler( string Formatter, float Value, int width = 0 )
    {
       string OutputStr = Value.ToString( Formatter );
       if( width > 0 ) OutputStr = OutputStr.PadLeft( width );
       Console.WriteLine( OutputStr );
    }
    . . .
    FormatHandler( "F1", Val, 5 );
    
    0 comments No comments