Write a Java Program to convert string variables to double

Java Program to convert string variables to double

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to convert string variables to double
Java Program to convert string variables to double

Write a Java Program to convert string variables to double

PROGRAM: Java Program to convert string variables to double

/*Java Program to convert string variables to double*/

1: Java Program to Convert string to double using parseDouble()

class Main {
public static void main(String[] args) {

// create string variables
String str1 = “23”;
String str2 = “456.6”;

// convert string to double
// using parseDouble()
double num1 = Double.parseDouble(str1);
double num2 = Double.parseDouble(str2);

// print double values
System.out.println(num1); // 23.0
System.out.println(num2); // 456.6
}
}

2: Java Program to Convert string to double using valueOf()

class Main {
public static void main(String[] args) {

// create string variables
String str1 = “6143”;
String str2 = “21312”;

// convert String to double
// using valueOf()
double num1 = Double.valueOf(str1);
double num2 = Double.valueOf(str2);

// print double values
System.out.println(num1); // 6143.0
System.out.println(num2); // 21312.0
}
}

3: Java Program to Convert a String containing comma to double

class Main {
public static void main(String[] args) {

// create string variables
String str = “614,33”;

// replace the , with .
str = str.replace(“,”, “.”);

// convert String to double
// using valueOf()
double value = Double.parseDouble(str);

// print double value
System.out.println(value); // 614.33
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *