# Problems when multiplying numbers from a string

• 09-06-2010, 02:29 AM
davetheant
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:
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:
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.
• 09-06-2010, 02:46 AM
Norm
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.
• 09-06-2010, 02:59 AM
davetheant
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?
• 09-06-2010, 03:01 AM
Norm
Quote:

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
• 09-06-2010, 03:23 AM
davetheant
You were exactly right! Atoi does seem to be a C method lol.. Would parseInt work?
• 09-06-2010, 03:42 AM
Fubarable
Quote:

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! :)