Re: converting 'char' to an integer



Joan wrote:

"Raymond DeCampo" <nospam@xxxxxxxxxxxx> wrote in message news:YiMKe.7386$rI6.5326@xxxxxxxxxxxxxxxxxxxxxxx


Joan wrote:


"Jeremy Watts" <jwatts1970@xxxxxxxxxxx> wrote in message news:1SJKe.5670$1F5.1069@xxxxxxxxxxxxxxxxxxxxxxx


Hi,

Sorry for some of these newbie questions ive been posting, but i really cant
get this to work. i have a Java 'char' (it will always be a number) defined
but want to convert it to an integer. How do I do this??


I have tried using 'digit()' and 'getNumericValue()' but seem to always get
an error message. Am I not importing the right class here? I've so far
imported java.lang.Character. Maybe I am misusing the statements. How
would you ordinarily do something like this?


I like this method

int i = '5' - '0';


I think the problems with that method include that other locales will have different characters that represent digits and it will fail for those locales.

If you don't care about internationalization or you know that you have one of the Arabic numerals 0 through 9 then go for it.

Although, again, I will say that your example would be improved by including variables. E.g.

char ch = getSomeChar();
int i = ch - '0';

Ray

Good point Ray. Can you give me an example where the set of digits
is not contiguous?

Hexadecimal.

Character.digit('a',16) is 10.

'a' - '0' is 49.

Patricia
.



Relevant Pages

  • Re: converting char to an integer
    ... i have a Java 'char' defined ... Am I not importing the right class here? ... locales will have different characters that represent digits and it will fail for those locales. ...
    (comp.lang.java.programmer)
  • Re: converting char to an integer
    ... Sorry for some of these newbie questions ive been posting, but i really cant ... i have a Java 'char' defined ... Am I not importing the right class here? ...
    (comp.lang.java.programmer)
  • converting char to an integer
    ... Sorry for some of these newbie questions ive been posting, but i really cant ... i have a Java 'char' defined ... Am I not importing the right class here? ...
    (comp.lang.java.programmer)
  • Re: converting char to an integer
    ... i have a Java 'char' defined but want to convert it to an integer. ... an error message. ... Am I not importing the right class here? ...
    (comp.lang.java.programmer)
  • Re: converting char to an integer
    ... Sorry for some of these newbie questions ive been posting, but i really cant ... i have a Java 'char' defined ... Am I not importing the right class here? ...
    (comp.lang.java.programmer)