This java tutorial focuses on an example on how to convert String to Double. In java API perspective, a Double is a wrapper class of primitive type double. Primitive data type is a double precision 64-bit floating point. This data type holds larger value than float, however please note that this data type should never be used for precise values or calculation but for handling decimal values this is already sufficient.
Why would we have the need to convert a String to Double object? Instead why don’t we just stick in assigning it into double in the first place. The answer would be what if the JAVA API or your company’s implementation is only throwing a String data type and your business requirements need to have Double data type. For example, the value would be taken from a text file which probably be read using an instance of Scanner class of java.util package which generally will give you String output. On this example source code, we would be showing how to do the conversion of String objects to Double data type.
Java String to Double Conversion example
One practical example of forcing us to use the conversion of String to Double is getting the user input from the console and do some computation which on this case the perimeter of a rectangle. On this example, we will be asking for two values from the user. One parameter is Length and the other is width. From these two values we are required to validate the values and if exception is thrown we should be able to handle it gracefully. To do the conversion we will be using the static method parseDouble(String input) of Double class. The parseDouble method accepts a String input and then give an output in Double data type.
package com.javatutorialhq.tutorial; import java.util.Scanner; /* * This sample code shows how to convert a String input to Double data type * Java tutorial with example source code */ public class StringToDouble { @SuppressWarnings("resource") public static void main(String[] args) { System.out.println("Enter the dimensions of a rectangle"); System.out.print("L:"); Scanner scanner = new Scanner(System.in); try{ // convert the string read from the scanner into Integer type Double length = Double.parseDouble(scanner.nextLine()); System.out.print("W:"); scanner = new Scanner(System.in); Double width = Double.parseDouble(scanner.nextLine()); // Printing the area of rectangle System.out.println("Perimeter of rectangle:"+2*(width+length)); } catch(NumberFormatException ne){ System.out.println("Invalid Input"); } finally{ scanner.close(); } } }
Sample output in running the String to Double Converter
Enter the dimensions of a rectangle L:123 W:12.3 Perimeter of rectangle:270.6