# Thread: Problems when multiplying numbers from a string

1. Member
Join Date
Sep 2010
Posts
47
Rep Power
0

## Problems when multiplying numbers from a string

Hello everyone. I am writing a program in which I have a string, called num, that is a very long number. I am trying to pull the first few digits of that number and multiply them together, however when I do, I get a very big result (billions of times larger than it should). Here is my code:
Java Code:
```int indx = 0; //just a variable for the index of the string
String num = "12345678901234567890";
int product = ((num.charAt(indx))*(num.charAt(indx + 1))*(num.charAt(indx + 2))*(num.charAt(indx + 3))*(num.charAt(indx + 4)));```
Since this didn't work, I put each in its own separate int and tried multiplying them again:
Java Code:
```    int aa = (num2.charAt(indx));
int ab = (num2.charAt(indx + 1));
int ac = (num2.charAt(indx + 2));
int ad = (num2.charAt(indx + 3));
int ae = (num2.charAt(indx + 4));
int aaaa = aa*ab*ac*ad*ae;
System.out.println(aaaa);```
And I still got the same result. When I print each digit separately, I get the right values, but when I multiply them, I get a crazy number. Please Help. Thanks in advance.

2. To see what values you are working with, extract a single character digit from the String and print it as an int.
The char '1' is not equal to the integer 1. You need to convert the characters to integer values. See the Character class and the Integer class for methods to do that.

3. Member
Join Date
Sep 2010
Posts
47
Rep Power
0
Thanks a lot, I had no idea that they were different. Upon doing a little research, I learned about a method called 'atoi'. Would this do the trick in my case?

4. Would this do the trick
Try it and see. Let us know if it works.

atoi looks like a c function. Go check your research again. You need to use a method of a Java class

5. Member
Join Date
Sep 2010
Posts
47
Rep Power
0
You were exactly right! Atoi does seem to be a C method lol.. Would parseInt work?

6. Originally Posted by davetheant
You were exactly right! Atoi does seem to be a C method lol.. Would parseInt work?
With numbers this big, you have no choice really but to use BigInteger (or BigDecimal).

edit: nope, if you're just using the digits of the number, then you can hold off BigInteger, but best be careful. With regards to Integer.parseInt(...), I'm with Norm: try it! :)
Last edited by Fubarable; 09-06-2010 at 04:03 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•