What is the best way to reproduce the behavior of something like this in C #?
// Converts decimal to a 0-padded string with minimum specified width and precision.
sprintf(out, "%0*.*lf", width, precision, decimal);
I have read the standard , custom and compound format strings, but I don't see anything good to achieve this.
The reason I ask is because I just stumbled upon this ugly piece of code in some code that I support where we need to format a bunch of decimal places according to the width and precision of the variables, as indicated by the external interface :
private static String ZEROS = "00000000000000000000000000";
public override string Format(decimal input, int width, int precision)
{
String formatString = ZEROS.Substring(0, width - precision - 1)
+ "." + ZEROS.Substring(0, precision);
return ToDecimal(input).ToString(formatString);
}
and I would like to replace it with something less terrible.
UPDATE
Since the final answer is buried in the comments, here it is:
public override string Format(decimal input, int width, int precision)
{
string.Format("{0," + width + ":F" + precision + "}", input).Replace(" ","0");
}
In my case, the input is always positive, so this also works:
public override string Format(decimal input, int width, int precision)
{
return input.ToString("F"+precision).PadLeft(width, 0);
}