Reputation: 1
public class Main
{
public static void main(String[] args)
{
System.out.println(digitofPi(0));
}
public static int digitofPi(int digit)
{
String x = String.valueOf(Math.PI);
char result = x.charAt(digit);
return result;
}
}
I'm trying to print out nth position of pi by converting pi to string, however it keeps printing out 51.
Upvotes: 0
Views: 190
Reputation: 409
You're converting the character to int, which means you're getting it's ASCII code. (Actually Unicode codepoint, but for your case it's the same.)
If you look at it, you'll see that the code of "0" is 48 and the code of "3" is 53. So you'd have to subtract 48 from it.
Upvotes: 0
Reputation: 75
This one will return 51
public static int digitofPi(int digit) {
String x = String.valueOf(Math.PI);
return x.charAt(digit);
}
Upvotes: -2
Reputation: 11153
Let's take your code step by step and let's consider that Pi = 3.1415
Math.PI = 3.1415
So, when you're
String x = String.valueOf(Math.PI);
Then
x = "3.1415"
And when you do this:
char result = x.charAt(digit);
Then result
becomes '3'
And if you return an int
from a char
, it's going to take its ASCII value, so:
'3' = 51
So you can either return char
or String
on your method
return result
Upvotes: 3
Reputation: 89294
You want to return a char
, not an int
, unless you want to display the ASCII character code of the digit.
public static char digitofPi(int digit) {
String x = String.valueOf(Math.PI);
char result = x.charAt(digit);
return result;
}
Note that you should remove the decimal point from the String
if you do not want it to be treated as the second digit.
String x = String.valueOf(Math.PI).replace(".", "")
Upvotes: 1