Search code examples
c#winformsvisual-studionumber-formatting

How to format numbers in scientific notation with powers in superscript


I need to write values like:

9.6 x 10²
9.6 x 10¹²

I need to know if there is a way to format numbers as above in a string.


Solution

  • As a follow up to my comment above - does something like this do what you require :

    public String FormatAs10Power(decimal val)
    {
      string SuperscriptDigits = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";
      string expstr = String.Format("{0:0.#E0}", val);
    
      var numparts = expstr.Split('E');
      char[] powerchars = numparts[1].ToArray();
      for (int i = 0; i < powerchars.Length; i++)
      {
        powerchars[i] = (powerchars[i] == '-') ? '\u207b' : SuperscriptDigits[powerchars[i] - '0'];
      }
      numparts[1] = new String(powerchars);
      return String.Join(" x 10",numparts);
    }
    

    See : https://dotnetfiddle.net/dX7LAF

    As per my comment above - the number is first converted to an exponential format string (https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#EFormatString), that string is then split on the exponential separator 'E'. The first array is the numeric part, the second the power of 10 to which it is raised - this is converted to superscript characters using one of the techniques of the link I gave (Convert a string/integer to superscript in C#), converted back to a string & the two parts combined using "x 10" as the new separator.

    I have assumed you want the value to single digit precision as per your example with no preceding + sign. If you need anything else you could pass the format as a parameter. The code for superscript + is '\u207A'. There is a link here (at the time of writing) giving the list of superscript codes : http://unicode.org/charts/PDF/U2070.pdf