简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM