Search code examples
c#tostring

ToString format for fixed length of output - mixture of decimal and integer


I'm writing some code to display a number for a report. The number can range from 1. something to thousands, so the amount of precision I need to display depends on the value.

I would like to be able to pass something in .ToString() which will give me at least 3 digits - a mixture of the integer part and the decimal part.

Ex:

1.2345 -> "1.23"
21.552 -> "21.5"
19232.12 -> "19232"

Using 000 as a format doesn't work, since it doesn't show any decimals, neither does 0.000 - which shows too many decimals when the whole part is larger than 10.


Solution

  • You could write an extension method for this:

    public static string ToCustomString(this double d, int minDigits = 3)
    {
        // Get the number of digits of the integer part of the number.
        int intDigits = (int)Math.Floor(Math.Log10(d) + 1);
        // Calculate the decimal places to be used.
        int decimalPlaces = Math.Max(0, minDigits - intDigits);
        
        return d.ToString($"0.{new string('0', decimalPlaces)}");
    }
    

    Usage:

    Console.WriteLine(1.2345.ToCustomString());    // 1.23
    Console.WriteLine(21.552.ToCustomString());    // 21.6
    Console.WriteLine(19232.12.ToCustomString());  // 19232
    
    Console.WriteLine(1.2345.ToCustomString(minDigits:4));    // 1.235
    

    Try it online.