twc
Posts: 129
Nickname: twc
Registered: Feb, 2004
|
|
Re: how do you convert a String to an int like this?
|
Posted: Mar 23, 2004 10:24 AM
|
|
java.lang.NumberFormatException.forInputString(NumberFormat Exception.java:48) > Is this not possible to do...!???!
You can't use the parseInt method to parse something that isn't an integer.
>If not then can I > convert the String to a float...!???!
Yes, as mausom pointed out, the Float and Double classes each have parsing methods that are similar, but return floating point values. Double is the more common choice, but it really doesn't matter.
After you parse to the float or double, it is fairly easy to convert to an int. But first you have to decide what to do about the fractional portion. If you just want to eliminate it, you can simply use a typecast.
int myInt = (int) myDouble;
But if you want to round the value, go into the Math class. It has a couple of rounding methods that you can choose from. I'm working from memory, but I think one is called rint(double) and that it does the traditional rounding to the nearest integer like we learned in grade school. Check the documentation. If you haven't downloaded it yet, you can view it online at http://java.sun.com/j2se/1.4.2/docs/api/index.html
>The > this.currentTemp needs to be a String for another part of > program to work in case you are wondering. Any help is > appreciated. Thanks!
Parsing Strings to get numeric values is pretty common. That is why there are already methods in place to handle the process. None of this will affect your original String.
|
|