I have a double, say r = 1.44, r - 1.0 is supposed to be 0.44, but I got 0.439999995, I think there is an overflow, but I don't know where I did wrong. I tried to use r - 1.0, r - 1, or (double)(r - 1.0), nothing works.
Thanks.
Probably I should make it more clearly. I am trying to solve this problem on Cracking the code interview:
Given a (decimal - e.g. 3.72) number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print “ERROR”
Here is my code based on the solution provided by the book:
public class DecimalToBinary {
public static String binary (String decimal){
if (decimal == null || decimal.length() == 0)
return decimal;
boolean hasPoint = false;
int pointP = 0;
if (decimal.contains(".")) {
hasPoint = true;
pointP = decimal.indexOf('.');
}
StringBuilder intString = new StringBuilder();
int intPart = Integer.parseInt(hasPoint ? decimal.substring(0, pointP) : decimal);
while (intPart > 0){
intString.append(intPart % 2);
intPart >>= 1;
}
if (!hasPoint)
return intString.toString();
StringBuilder decString = new StringBuilder();
double decPart = Double.parseDouble(decimal.substring(pointP));
if (decPart == 0)
return intString.toString();
while (decPart > 0){
if (decPart == 1) {
decString.append(1);
break;
}
double r = decPart * 2.0;
System.out.println("r " + r);
if (r >= 1) {
decString.append(1);
decPart = (double)(r - 1);
System.out.println("dec " + decPart);
}
else {
decString.append(0);
decPart = r;
}
}
return intString.toString() + "." + decString.toString();
}
public static void main(String[] args) {
System.out.println(binary("3.72"));
}
}
Then I realize it's not giving me the correct answer, and I found out that it is because of the r. Since my goal is to print out the variable, so probably I would need some other approach?