How do I save the values of a String in a Double variable?

1

I have a String with the value x inside it

(String value="x")

I need to pass this value to a Double Variable, how do I pass the x value of the String to the variable? So if I convert from String to Double the value of the Double variable is null.

Balance = Double.parseDouble (value);

asked by anonymous 22.06.2016 / 20:12

1 answer

3

The parseDouble method is the most used to do this type of conversion.

public class ConvertStringToDouble {
  public static void main(String[] args) {
    String aString = "700";
    double aDouble = Double.parseDouble(aString);

    System.out.println(aDouble);
  }
}
  

You can also make CAST to convert to your type.

double aDouble = (Double)aString;
  

Using Double.valueOf

The Static method Double.valueOf () will return a Double object while maintaining the value of the specified string.

Syntax

String numberAsString = "153.25";
double number = Double.valueOf(numberAsString);
System.out.println("The number is: " + number);
  

Convert using new Double (String) .doubleValue ()

String numberAsString = "153.25";
Double doubleObject = new Double(numberAsString);
double number = doubleObject.doubleValue();

We can shorten to:

String numberAsString = "153.25";
double number = new Double(numberAsString).doubleValue();

Or;

double number = new Double("153.25").doubleValue();
  

Converts using DecimalFormat

The java.text.DecimalFormat class is a class that can be used to convert a number to its String representation. It can also be used in reverse - it can parse a String in its numeric representation. Example

String numberAsString = "153.25";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
   double number = decimalFormat.parse(numberAsString).doubleValue();
   System.out.println("The number is: " + number);
} catch (ParseException e) {
   System.out.println(numberAsString + " is not a valid number.");
}

Note: If your string contains , in place of . , make a replace before attempting to convert.

>
String number = "123,321";
double value = Double.parseDouble(number.replace(",",".") );

See worked here.

    
22.06.2016 / 20:37