Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find numeric value of a digit character in C#

There are several ranges in Unicode characters that represent digits, for which char.IsDigit returns true. For example:

bool b1 = char.IsDigit('\uFF12');    // full-width '2' -> true
bool b2 = char.IsDigit('\u0665');    // true
bool b3 = char.IsDigit('5');         // true

I'm looking for a way to get the numeric equivalent of such characters. Note that int.Parse(...) DOES NOT work, as it expects the input characters to be in the base unicode range ('0' .. '9').

This is equivalent to Java's Character.digit(...) behavior.

Since the .NET framework's char.IsDigit method correctly identifies such characters as digits, I'm expecting it to have this functionality as well, but I couldn't find anything.

like image 821
Iravanchi Avatar asked Sep 27 '12 21:09

Iravanchi


1 Answers

Have you tried Char.GetNumericValue? (I'm just booting up my Windows laptop to check :)

EDIT: Just tried it - looks like it works:

Console.WriteLine(char.GetNumericValue('\uFF12'));  // 2
Console.WriteLine(char.GetNumericValue('\u0665'));  // 5
Console.WriteLine(char.GetNumericValue('5'));       // 5

Note that this doesn't just include digits - it's any numeric character. However, IsDigit is just for digits. For example:

// U+00BD is the Unicode "vulgar fraction one half" character
Console.WriteLine(char.IsDigit('\u00bd'));         // False
Console.WriteLine(char.GetNumericValue('\u00bd')); // 0.5
like image 154
Jon Skeet Avatar answered Sep 21 '22 06:09

Jon Skeet