I’m making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
Other answers are correct, you could use a
java.text.NumberFormat(JavaDoc) to format your output. Usingprintfis also an option for formatting, similar toNumberFormat. But I see something else here. It looks like you mixed up your data types: Innq = (long) Math.pow(2l, 1000l);you are already truncating the double return value from Math to a long. Then you should use
longas data type instead ofdoublefor the conversion. So useLong.toString(long), this will not add any exponent output.Use
Long.toString(nq)instead ofDouble.toString(nq); in your code.