Search code examples
c#string-formattingdecimal-point

String.Format - How can I format to x digits (regardless of decimal place)?


I need to format a floating point number to x characters (6 in my case including the decimal point). My output also needs to include the sign of the number

So given the inputs, here are the expected outputs

1.23456   => +1.2345

-12.34567 => -12.345

-0.123456 => -0.1234

1234.567  => +1234.5

Please assume there is always a decimal place before the last character. I.e. there will be no 12345.6 number input - the input will always be less than or equal to 9999.9.

I'm thinking this has to be done conditionally.


Solution

  • Here's a transparent way to do it without format strings (except for "F"):

      static void Main()
      {
         double y = 1.23456;
         Console.WriteLine(FormatNumDigits(y,5));
         y= -12.34567;
         Console.WriteLine(FormatNumDigits(y,5));
         y = -0.123456;
         Console.WriteLine(FormatNumDigits(y,5));
         y = 1234.567;
         Console.WriteLine(FormatNumDigits(y,5));
    
         y = 0.00000234;
         Console.WriteLine(FormatNumDigits(y,5));
    
         y = 1.1;
         Console.WriteLine(FormatNumDigits(y,5));
      }
    
    
      public string FormatNumDigits(double number, int x) {
         string asString = (number >= 0? "+":"") + number.ToString("F50",System.Globalization.CultureInfo.InvariantCulture);
    
         if (asString.Contains('.')) {
            if (asString.Length > x + 2) {
               return asString.Substring(0, x + 2);
            } else {
               // Pad with zeros
               return asString.Insert(asString.Length, new String('0', x + 2 - asString.Length));
            }
         } else {
            if (asString.Length > x + 1) {
               return asString.Substring(0, x + 1);
            } else {
               // Pad with zeros
               return asString.Insert(1, new String('0', x + 1 - asString.Length));
            }
         }
      }
    

    Output:

      +1.2345
      -12.345
      -0.1234
      +1234.5
      +0.0000
      +1.1000
    

    EDIT

    Notice that it does not chop off trailing zeros.