# Binary-to-Decimal Conversion (Precision Problem)

• 09-06-2010, 07:18 PM
Binary-to-Decimal Conversion (Precision Problem)
This semester I'm taking a class in Number Theory and Intro to Java. As a way to study both I'm trying to make a program that can convert values from one number sytem (ie binary, hexadecimal, octal) to decimal.

One step in this has me needing to convert a double (the number to be converted) to a string. From there I use .charAt(int) to pick each digit and multiply it by the correct power of 2 .
(ie: ABCD = a*2^3 + b*2^2 + c*2^1 + d*2^0)

When I do convert the double to a string, the portion past the floating point is changed slightly. For example, the number I enter to be converted from binary to decimal as 10110.1101 is rounded by the computer in the conversion process to the value 10110.110099 (which obviously doesn't play by the rules of binary lol).

So I'm looking for a way to stop the value from being changed, during the conversion to string process. Or I'd like to find a way around having to convert to a string in the first place?

Any ideas are greatly appreciated.
I've already tried double=Math.floor(double*1000)/1000, and a few other normally clever fixes, but to no success.

• 09-06-2010, 08:13 PM
JosAH
Forget about raising numbers to a power and have a look at the Integer class; it has all the methods you want or need.

kind regards,

Jos
• 09-06-2010, 09:32 PM
Norm
Is your project to write methods that are available in the Integer class
or is it to do something at a higher lever using the Integer class methods?

Quote:

a way to stop the value from being changed
Don't use floating point numbers. Do it all in whole numbers.

Quote:

converted from binary to decimal as 10110.1101 is rounded by the computer in the conversion process to the value 10110.110099
How did that work? Would the decimal value would be: (16+4+2).(1/2+1/4+1/16)
• 09-07-2010, 03:20 AM