Converting chars (Casting vs. .getNumericValue)

寵の児 提交于 2020-12-25 05:25:20

问题


Why is it that casting (int) can convert chars of a symbol to int properly, but "Character.getNumericValue('someSymbolCharValue');" can't?

E.g. "Character.getNumericValue('?');" will return -1 even though the char can be presented as int with "(int) '?'" where it will return 63


回答1:


A character's "numeric value" is not its ASCII/Unicode index value. The Character.getNumericValue method will attempt to convert the char to an int by applying the character's numeric meaning:

Returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50. The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

It is expected that getNumericValue will not agree with casting the char to an int.



来源:https://stackoverflow.com/questions/26185452/converting-chars-casting-vs-getnumericvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!