Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the "java" way of converting chars (digits) to ints [duplicate]

Tags:

java

integer

char

Given the following code:

    char x = '5';     int a0 = x - '0'; // 0     int a1 = Integer.parseInt(x + ""); // 1     int a2 = Integer.parseInt(Character.toString(x)); // 2     int a3 = Character.digit(x, 10); // 3     int a4 = Character.getNumericValue(x); // 4     System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4); 

(version 4 credited to: casablanca)

What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)

We are not converting the actual numerical value of the char, but the value of the representation.

Eg.:

convert('1') -> 1 convert('2') -> 2 .... 
like image 255
Andrei Ciobanu Avatar asked Oct 16 '10 17:10

Andrei Ciobanu


People also ask

Can I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.


2 Answers

How about Character.getNumericValue?

like image 67
casablanca Avatar answered Sep 20 '22 15:09

casablanca


I'd strongly prefer Character.digit.

like image 27
jacobm Avatar answered Sep 21 '22 15:09

jacobm