6

Is it possible to write 10² or 10³ in C#?

For example in a label or Console output.

I also want use it for other powers (104, 105, ...).

Something like:

string specialNumber = string.Format("10^4");
System.Console.Write(specialNumber);
Bit
  • 1,068
  • 1
  • 11
  • 20
user2261524
  • 415
  • 3
  • 10
  • 17

5 Answers5

8

This is really two different questions. One for the console, and one for a GUI app. I'm choosing to cover the console.

If you just need powers 2 and 3 you can do this:

Console.WriteLine("10²");
Console.WriteLine("10³");

This makes use of characters U+00B2 and U+00B3.

If it turns out that you require different powers then you are out of luck at the console. Whilst there are Unicode characters for other numerals, font support is poor and you will have no success with code like this:

Console.WriteLine("10⁴");
Console.WriteLine("10⁵");
Console.WriteLine("10⁶");
// etc.

Many commonly used console fonts do not include superscript glyphs for these characters. For example, this is what it looks like on my machine using Consolas:

enter image description here

If you are using the default console font of Lucinda Console, then the results are the same.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

Here's superscripts and subscripts

wikipedia

And here's how to escape unicode characters in c#

MSN

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • No need to escape them when you can just type them. It's a Windows keyobard question, not a C# question – Panagiotis Kanavos Jun 27 '13 at 13:16
  • Whilst you can write the program, the console window won't display anything meaningful – David Heffernan Jun 27 '13 at 13:16
  • It will if you have the proper system locale configured. Once again, it's a matter of Windows configuration, not of C# programming – Panagiotis Kanavos Jun 27 '13 at 13:17
  • @PanagiotisKanavos Can you elaborate? – David Heffernan Jun 27 '13 at 13:18
  • 1
    Unless you specifically change your console font to a Unicode font, Windows will display character data using the codepage specified by the system locale, just like good old DOS. Some codepages replace the higher ASCII codes with international characters rather than graphic characters. If you don't see the high ASCII codes as you expect, it's because your system locale has different characters in these positions – Panagiotis Kanavos Jun 27 '13 at 13:25
  • @PanagiotisKanavos Please give an example of a Unicode font. Because I don't think your comment is particularly accurate. Plenty of fonts have glyphs for many but not all Unicode characters. – David Heffernan Jun 27 '13 at 13:33
  • A Unicode font is not required to have ALL available Unicode characters and many fonts include only a subset to conserve space. It is required to match the proper 16-bit words to the proper characters. Arial is a pretty complete font, but it's 7 times larger than Lucida Console – Panagiotis Kanavos Jun 27 '13 at 15:36
1

If you'd like a complete solution (which is able to format the string based on the '^' character), then you'll have to roll your own. Or... you can use the one I just rolled up for you:

The function to replace an input character with the corresponding superscript character (notice that it is an extension function):

public static char ToSuperscript( this char numericChar )
{
    switch ( numericChar )
    {
        case '0':
            return '\u2070';
        case '1':
            return '\u00B9';
        case '2':
            return '\u00B2';
        case '3':
            return '\u00B3';
        case '4':
            return '\u2074';
        case '5':
            return '\u2075';
        case '6':
            return '\u2076';
        case '7':
            return '\u2077';
        case '8':
            return '\u2078';
        case '9':
            return '\u2079';
        default:
            return numericChar;
    }
}

Now, I like to use LINQ, so I need a custom extension method to handle the scan (thanks go the MisterMetaphor for directing me to this function):

public static IEnumerable<U> Scan<T, U>( this IEnumerable<T> input, Func<U, T, U> next, U state )
{
    yield return state;
    foreach ( var item in input )
    {
        state = next( state, item );
        yield return state;
    }
}

A custom extension function using LINQ to apply the superscript formatting:

public static string FormatSuperscripts( this string unformattedString )
{
    return new string(
            unformattedString
            .ToCharArray()
            .Scan(
                ( state, currentChar ) =>
                    new
                    {
                        Char = state.IsSuperscript ? currentChar.ToSuperscript() : currentChar,
                        IsSuperscript = ( currentChar >= '0' && currentChar <= '9' && state.IsSuperscript ) || currentChar == '^',
                        IncludeInOutput = currentChar != '^'
                    },
                new
                {
                    Char = ' ',
                    IsSuperscript = false,
                    IncludeInOutput = false
                }
            )
            .Where( i => i.IncludeInOutput )
            .Select( i => i.Char )
            .ToArray()
        );
}

And, finally, calling the function:

string l_formattedString = "10^27 45^100".FormatSuperscripts();

Output:

10²⁷ 45¹⁰⁰

As already noted, however, the console will not correctly display unicode characters \u2074 - \u2079, but this function should work in scenarios where the font supports these characters (such as WPF, ASP.NET with a modern browser, etc)

You could easily modify the above LINQ query to apply other formattings as well, but I will leave that exercise to the readers.

Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123
  • Great formating function. This `Scan` function... does it implement a finite state machine in the iterator? Clever. – Medinoc Jun 28 '13 at 09:11
0

I don't think there is an automatic stuff, but you can write a conversion function:

static char ToSuperscriptDigit(char input)
{
    switch(input)
    {
    case '0': return '\u2070';
    case '1': return '\u00B9';
    case '2': return '\u00B2';
    case '3': return '\u00B3';
    case '4': return '\u2074';
    case '5': return '\u2075';
    case '6': return '\u2076';
    case '7': return '\u2077';
    case '8': return '\u2078';
    case '9': return '\u2079';
    default: return input;
    }
}

string ToSuperscriptDigits(string input)
{
    if(input==null)
        return null;
    StringBuilder sb = new StringBuilder(input.Length);
    foreach(char c in input)
        sb.Append(ToSuperscriptDigit(c));
    return sb.ToString();
}

Note that not all fonts render these characters equally: In Arial Unicode MS they all have the same style, but in plain old Arial, Lucida Console, Courier New etc., 1-3 are different from the rest. In Courier New, 4-0 aren't even monospaced!

Medinoc
  • 6,577
  • 20
  • 42
0

If the question is how to enter the ² and ³ characters inside a text - just type them. It has nothing to do with C#, it has to do with your keyboard. In my case (Greek keyboard layout), I pressed Right Alt + Right Ctrl + 2 for ² or Right Alt + Right Ctrl + 3 for ³.

If your layout doesn't work this way, you can use the Character Map built-in utility in Windows to find the shortcuts used for entering special characters. ² is Alt+0178 in the numeric keypad, ³ is Alt+0179

Some keyboards even mark the Right Alt as "Alt GR" to show it's for entering "Graphics" characters.

All special characters were entered using the methods described.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236