Difference between Char.IsDigit() and Char.IsNumber() in C#


Question

What's the difference between Char.IsDigit() and Char.IsNumber() in C#?

1
139
2/26/2013 9:37:26 AM

Accepted Answer

Char.IsDigit() is a subset of Char.IsNumber().

Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.

Note that there are quite a few characters that IsDigit() returns true for that are not in the ASCII range of 0x30 to 0x39, such as these Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙'.

This snippet of code tells you which code points differ:

static private void test()
{
    for (int i = 0; i <= 0xffff; ++i)
    {
        char c = (char) i;

        if (Char.IsDigit( c) != Char.IsNumber( c)) {
            Console.WriteLine( "Char value {0:x} IsDigit() = {1}, IsNumber() = {2}", i, Char.IsDigit( c), Char.IsNumber( c));
        }
    }
}
141
12/12/2013 5:01:04 AM

I found the answer:

Char.IsNumber() determines if a Char is of any numeric Unicode category. This contrasts with IsDigit, which determines if a Char is a radix-10 digit.

Valid numbers are members of the following categories in UnicodeCategory:

  1. DecimalDigitNumber
    Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation "Nd" (number, decimal digit). The value is 8.
  2. LetterNumber
    Number represented by a letter, instead of a decimal digit, for example, the Roman numeral for five, which is "V". The indicator is signified by the Unicode designation "Nl" (number, letter). The value is 9.
  3. OtherNumber
    Number that is neither a decimal digit nor a letter number, for example, the fraction ½. The indicator is signified by the Unicode designation "No" (number, other). The value is 10.

Conclusion

  • Char.IsDigit:
    Valid digits are members of the DecimalDigitNumber category only.
  • Char.IsNumber:
    Valid numbers are members of the DecimalDigitNumber, LetterNumber, or OtherNumber category.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon