parseInt(String) is a method used to convert the string into its equivalent integer value.But this should be applied with care.One should use it only when u are sure the string contains only numerals. eg String s="1234" int i=Integer.parseInt(s); its perfect but String s="abcd" int i=Integer.parseInt(s); Its not right.
Younes Essouabni
Ranch Hand
Joined: Jan 13, 2002
Posts: 479
posted
0
yes vdeepak is right. I didn't pay attention. I should have done int nb=Integer.parseInt(s)// Where s="1234" So this method convert a string to an int. But you can convert a string to a double too, like this: Double nb=Double.parseDouble(s)
You can cast an int to a double, but not the way you've suggested. Firstly, Double is a wrapper class and is treated as an object not a primitive value. There's a big difference between Double and double. Additionally, there is no parseDouble() method available in the Double class. When using explicit casts you need to understand the difference between a narrowing conversion and a widening conversion. You can't explicitly cast a double value to an int, but, you can cast an int to a double. A good book that describes this better than I can is "The Complete Java 2 Certification Guide" published by Sybex. Here's some sample code to cast the int i to a double. public class NumberCasts { static String s="1234"; static int i=Integer.parseInt(s); static double d = (double)i; public static void main(String[] args) {
System.out.println("Variable d = " + d); } } The output is "Variable d = 1234.0"
Younes Essouabni
Ranch Hand
Joined: Jan 13, 2002
Posts: 479
posted
0
Sorry if my post was confused. My english is not fluent. In fact I was talking about string not int.
int nb=Integer.parseInt(s)// Where s="1234"
You can see that 1234 is between quote. It is a string. YOU SAID
Additionally, there is no parseDouble() method available in the Double class.
parseDouble public static double parseDouble(String s) throws NumberFormatExceptionReturns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double. Parameters: s - the string to be parsed. Returns: the double value represented by the string argument. Throws: NumberFormatException - if the string does not contain a parsable double. Since: 1.2 See Also: valueOf(String)
Here's some sample code to cast the int i to a double. public class NumberCasts { static String s="1234"; static int i=Integer.parseInt(s); static double d = (double)i; public static void main(String[] args) { System.out.println("Variable d = " + d); } } The output is "Variable d = 1234.0"
You don't need an expicit cast when assigning an int value to a double variable. The following code will also work fine .
Younes Essouabni
Ranch Hand
Joined: Jan 13, 2002
Posts: 479
posted
0
Originally posted by Shivaji Marathe: As stated by Brent