t e m p o r a l 
 d o o r w a y 

Converting Strings to Numbers And Back

 

Oddly enough, this isn't covered very well in the books and documentation I've read. And yet it is critical to getting numeric data from things like edit controls into your program.

The key lies not in the String class, which does not have (for instance) a toDouble() method or a (double) cast (who knows why not?)

Instead, a group of object wrapper classes supply the needed capabilities:

  • Character
  • Boolean
  • Number
  • Integer
  • Long
  • Float
  • Double

(Note that the built-in types have a first letter in lower case (i.e. "double")).

To convert from a String to the desired type, use that type's "parse" function - for instance parseInt(String s) or parseDouble(String s). In an expression, this might look like:

double someDouble = Double.parseDouble(someEditText.getText());

Again, it remains a mystery as to why the Double type does not have a String parameter constructor. Note that the Double class does have a (double) cast, which is implicitly invoked in the expression above.

Naturally, it can be useful to return the number to a string representation. For that, the pattern is:

String someString = Double(someDouble).toString();

This can, of course, be used to load a control:

someEditText.setText(Double(someDouble).toString());

Once you know about this, it is simple - but finding out about it is something else again.

Copyright © 2004 by Mark Cashman (unless otherwise indicated), All Rights Reserved