Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character.getNumericValue() issue

I'm probably missing something, but why are the two numeric values equal to -1?

System.out.println(Character.getNumericValue(Character.MAX_VALUE));
System.out.println(Character.getNumericValue(Character.MIN_VALUE));

Returns:

-1
-1
like image 837
George Avatar asked Jan 27 '10 15:01

George


People also ask

What does character getNumericValue do?

GetNumericValue(Char)Converts the specified numeric Unicode character to a double-precision floating point number.

How do I find the value of a char in a number?

If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String. valueOf(char) method.

How do you find the numeric value of a character in Java?

The getNumericValue(int codePoint) method returns the numeric value of the character, as a non-negative int value. This method will return -2 if the character has a numeric value but the value cannot be represented as a non-negative int value. The method will return -1 if the character has no numeric value..


3 Answers

getNumericValue() only applies to characters that represent numbers, such as the digits '0' through '9'. As a convenience, it also treats the ASCII letters as if they were digits in a base-36 number system (so 'A' is 10 and 'Z' is 35).

This one fools a lot of people. If you want to know the Unicode value of a character, all you have to do is cast it to int:

System.out.println((int)Character.MAX_VALUE);
System.out.println((int)Character.MIN_VALUE);
like image 59
Alan Moore Avatar answered Sep 24 '22 19:09

Alan Moore


getNumericValue() will convert characters that actually represent numbers (like the "normal" digits 0-9, but also numerals in other scripts) to their numeric value. The Characters represented by Character.MAX_VALUEand Character.MIN_VALUE do not have such a numeric value; they are not numerals. And according to the API doc:

If the character does not have a numeric value, then -1 is returned.

like image 40
Michael Borgwardt Avatar answered Sep 22 '22 19:09

Michael Borgwardt


.. just because \u0000 and '\uffff` don't represent a digit and don't have a numeric value.

I guess you were looking for the 16bit value of the char, but for this we can simply cast:

int value = (int) Character.MAX_VALUE;
like image 40
Andreas Dolk Avatar answered Sep 24 '22 19:09

Andreas Dolk