Hi I have following float point value in base 10: 0.625. I need to convert this value in base 10 to binary format which is: 0.101. Algorithm I found is below. It works, but I am not understanding why this works. Could someone please explain to be why the code below works? I am aware that numbers after the decimal point is computed in the manner such that 1/2^n where n is count from the decimal point. Thanks.
To clarify, I need to know the reasoning behind the mathematical formula. Not stepping through the code.
private static String floatToBinaryString( double n ) {
String val = "0.";
while ( n > 0 ) {
double r = n * 2;
if( r >= 1 ) {
val += "1";
n = r - 1;
}else{
val += "0";
n = r;
}
}
return val;
}