String to double

If the size of an int (-2^31) isn't big enough you may need to consider using primitive type long or Long object when converting from a string. In this example we will show how to convert a string to a primitive double, object Double and vise versa. Just like when you change a string to an int you will need to handle NumberFormatException in the instance your string has both numeric and characters. If you are stuck with a chars among digits you could use a regex to obtain all numerals.

String to primitive double

@Test
public void string_to_double_primitive() {

    String myString = "2";

    double variable = Double.parseDouble(myString);

    assertEquals(2, variable, 0);
}

Primitive double to string

@Test
public void primitive_double_to_string() {

    double number = 2;

    assertEquals("2.0", String.valueOf(number));
}

StringBuffer to primitive double

@Test
public void stringbuffer_to_primitive_double() {

    StringBuffer buffer = new StringBuffer("2");

    assertEquals(2, Double.parseDouble(buffer.toString()), 0);
}

Stringbuilder to double

@Test
public void stringbuider_to_double() {

    StringBuilder builder = new StringBuilder("2");

    assertEquals(2, Double.parseDouble(builder.toString()), 0);
}

Double object to string

@Test
public void double_object_to_string() {

    Double doubleToString = Double.valueOf("2");

    assertEquals("2.0", doubleToString.toString());
}

String to double object

@Test
public void string_to_double_object() {
    
    Double stringToDoubleObject = Double.parseDouble("2");
    
    assertEquals(new Double(2), stringToDoubleObject);
}