How to save the values of a String in a Double variable?

Asked

Viewed 759 times

1

I have a string with the x value inside it

(String value = "x")

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

balance = Double.parseDouble(value); <--- After conversion the value becomes null

There is a way to collect this value and save in a Double variable?

  • 1

    How is it null? Here it occurred normal, see: https://ideone.com/BZ0T0z

  • You want to turn an 'x' value into String, for example '1.2', to double or want to actually turn 'x' to double?

  • Let’s say the value of X is: String x = 700; How do I pass this value (700) to a Double variable?

  • What has in its value variable before you to it for the Double.parseDouble?

  • http://stackoverflow.com/questions/5769669/convert-string-to-double-in-java

  • http://stackoverflow.com/questions/13166386/parsing-string-to-double-java

  • Alexandre, see the example of the link I sent, no problem. This method works normally.

Show 2 more comments

1 answer

3

The parseDouble method is the most used to make 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 do the CAST to convert to your type.

double aDouble = (Double)aString;

Using Double.valueOf

The static method Double.valueOf() will return a Double object holding the value of the specified sequence .

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 it 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 numerical 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.");
}

Obs: if your string contained , in place of . , the ideal and make a replace before trying converts.

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

See worked here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.