In this post, let us learn how to convert the strings to numbers like int, float, double and vice versa. We will also learn how to convert the int, float, double to each other. Below example will illustrate how to convert and type cast the numbers in Java.
``````
package numbers;

/**
* Created by ssalunke on 14/04/2016.
*/
public class NumberConversionCasting {
public static void main(String [] args) throws Exception {

System.out.println(new Double("120.11").doubleValue());

//Converting String to integer
String amount = "2323";
System.out.println("String converted into int -> "
+ Integer.parseInt(amount));

//Converting String to double
amount = "232323.4545";
System.out.println("String converted into double -> "
+ Double.parseDouble(amount));

//Converting String to double
double cost = 232323.4545;
System.out.println("double converted into string -> "
+ String.valueOf(cost) instanceof String);

//Converting string containing \$ to pure number.
// Remove all special characters before
amount = "\$87282.38";
amount = amount.replaceAll("\\$","");
System.out.println("After replacing the \$ -> "
+ Double.valueOf(amount));

//converting the number to string
double d = 78287.22;
System.out.println("String representation of double is -> "
+ String.valueOf(d));

//casting double to int
int x = (int) d;
System.out.println("After casting double to integer -> " + x);

}
}
``````
Here is the output of above example.
``````
120.11
String converted into int -> 2323
String converted into double -> 232323.4545
true
After replacing the \$ -> 87282.38
String representation of double is -> 78287.22
After casting double to integer -> 78287
``````

Web development and Automation testing

solutions delivered!!