Cuchulainn
Cuchulainn

Reputation: 49

Converting double to String, getting error saying I can't convert String to double

I think I might be going insane. I wrote a simple method, taking a double, converting to string, taking out the decimal and reversing the order of the numbers. Every time I run it, I get an error saying that I can't change a String to a double, which is true, but also the complete opposite of what I'm doing. I've tried double += ""; and double = Double.toString(double);, and I get the same error. The complete method:

   public static String favNumber(double bank) {
      bank = Double.toString(bank);
      bank = bank.replace('.',"");
      String ret = "";
      int end = bank.length() - 1;
      for(int i = end; i >= 0; i--) {
         char add = bank.charAt(i);
         ret += add;
      }
      return ret;
   }

Additional stuff: I swear the identifier names make sense in the grand scheme of my code (for a school assignment), and I am not allowed to use StringBuilder, hence the for loop.

Upvotes: 0

Views: 1196

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

In your code, the variable bank has type double - you've declared it thus in the first set of parentheses.

Then on the second line, you take an expression of type String - namely Double.toString(bank), and try to assign it to the variable bank. That is, you're trying to assign a value of type String to a variable of type double - and that's what the compiler is preventing you from doing.

Upvotes: 4

slipperyseal
slipperyseal

Reputation: 2778

You have attempted to assign the String returned by Double.toString back to bank which was the original double variable. Here I have used two different variables, one a double and one a String...

public static String favNumber(double thedouble) {
  String bank = Double.toString(thedouble);
  bank = bank.replace('.',"");
  String ret = "";
  int end = bank.length() - 1;
  for(int i = end; i >= 0; i--) {
     char add = bank.charAt(i);
     ret += add;
  }
  return ret;
}

Upvotes: 3

Stefan
Stefan

Reputation: 2395

bank is of type double. Then you cannot assign a String value to it. Do this:

String bankStr = Double.toString(bank);

Upvotes: 3

Related Questions