0

I'm not searching for clean and good looking code.

I'm curious if there is a way to do it with less conversions and function calls

Explaining all passages

public static int Double (double d, int p) {
    String dToString = d+"";
    char stringToChar = dToString.charAt(p);
    String charToString = stringToChar+"";
    int stringToInt = Integer.parseInt(charToString);
    return stringToInt;
}

Condensed and ugly version

public static int Double (double d, int p) {
    return Integer.parseInt(((d+"").charAt(p))+"");
}

}

AcjnN
  • 1
  • 1
  • 3
    Something like this? https://stackoverflow.com/questions/19194257/return-the-nth-digit-of-a-number – TomStroemer Aug 04 '20 at 13:24
  • You know that your second snippet will always throw `StringIndexOutOfBoundsException`, right? – Amongalen Aug 04 '20 at 13:27
  • You could use `Character.getNumericValue(stringToChar)` – Andy Turner Aug 04 '20 at 13:42
  • "condensed and ugly version" is different. I suspect you mean `return Integer.parseInt((d+"").charAt(p)+"");`. You could have used `return Integer.parseInt((d+"").substring(p, p+1));` alternatively, or `Double.toString(d).substring(...)` etc. – Andy Turner Aug 04 '20 at 13:44
  • Thanks, yes, I didn't copy & paste and forgot the parentesis but yep, that's what I meant. I'll try the two other alternatives, thanks :) – AcjnN Aug 04 '20 at 21:10

0 Answers0