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.