Besides just filling in the string, you can do even more complex math to determine the number of digits:
String FormatField(Int32 fieldWidth, Decimal value) { var integerPartDigits = value != Decimal.Zero ? (int) Math.Log10((Double) value) + 1 : 1; var fractionalPartDigits = Math.Max(0, fieldWidth - integerPartDigits - 1); return value.ToString("F" + fractionalPartDigits); }
Please note that if the value is negative or has an integer part with one smaller digit than the field width, you will not get the desired result. However, you can change the code to accommodate these cases based on how you want to format and align these numbers.
source share