int main(){
long double fraDecimal,fraBinary,bFractional = 0.0,dFractional,fraFactor=0.1;
long int dIntegral,bIntegral=0;
long int intFactor=1,remainder,temp,i;
printf("Enter any fractional decimal number: ");
scanf("%Lf",&fraDecimal);
dIntegral = fraDecimal;
dFractional = fraDecimal - dIntegral;
while(dIntegral!=0){
remainder=dIntegral%2;
bIntegral=bIntegral+remainder*intFactor;
dIntegral=dIntegral/2;
intFactor=intFactor*10;
}
for(i=1;i<=12;i++){
dFractional = dFractional * 2;
temp = dFractional;
bFractional = bFractional + fraFactor* temp;
if(temp ==1)
dFractional = dFractional - temp;
fraFactor=fraFactor/10;
}
fraBinary = bIntegral + bFractional;
printf("Equivalent binary value: %Lf",fraBinary);
return 0;
}
Asked
Active
Viewed 88 times
3

kiran Biradar
- 12,700
- 3
- 19
- 44

electra3.14
- 31
- 1
-
refer this one [here](https://stackoverflow.com/questions/52660296/why-does-double-in-c-print-lesser-decimal-digits-that-c) – asio_guy Oct 05 '18 at 07:41
-
You need mention the width of decimal points you want to print as `%.[width]f `example: `%.4f`-> this will print the 4 decimal points. – danglingpointer Oct 05 '18 at 07:47
1 Answers
0
Instead of this:
printf("Equivalent binary value: %Lf",fraBinary);
Try this:
printf("Equivalent binary value: %.12Lf", fraBinary);
Also note that it's not always displaying the last number correctly. At least on my machine, where long double
is 8 bytes. It seems like this is pushing long double
's precision to the limit. And sure enough, this states that
The 53-bit significand precision gives from 15 to 17 significant decimal digits precision

Blaze
- 16,736
- 2
- 25
- 44
-
For what input is the program not displaying the last number correctly, what is the output you observe, and what is the output you would expect to be correct? – Eric Postpischil Oct 05 '18 at 11:05
-
@EricPostpischil tried it with the input `44.44`, got `101100.011100001007`, expected `101100.011100001010`. I suppose 128 bit floats would be required to solve this issue, barring a more complicated workaround. – Blaze Oct 05 '18 at 11:12
-
Thanks, now I see the problem is they are accumulating “binary” digits in a “decimal” numbering inside a binary floating-point format, and they push it too far. It would have been simpler just to accumulate characters in a string. – Eric Postpischil Oct 05 '18 at 11:37
-
Forgot to mention, I have already tried %.12Lf but when I do that it gives me 12 decimal place but it doesn't calculate anything. for example if i give input 4.404 the output becomes 0.000000000000 for any input. – electra3.14 Oct 05 '18 at 23:55