# Thread: HELP! Changing the base of a floating point number..

1. ## HELP! Changing the base of a floating point number..

Hello,
I am studying C in school and we have this book ANSI C written by Gary J. Bronson, which isnt very helpful..

So the question;
I am able to write a code which can change an integer in to whatever base I like but cant really do that with a decimal..(eg: 2.54) can someone please help me ??
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)

{
int number,base,reminder,numbits=0,highestfactor,bit;

scanf("%d",&number);
printf("please enter the base the number will be converted to:");
scanf("%d",&base);

reminder=number;
while(reminder!=0)
{
reminder=reminder/base;

numbits++;
}

highestfactor=numbits-1;
int i=0;

while(i<numbits)
{

int pwr=pow(base,highestfactor);
bit=number/pow(base,highestfactor);
number=number%pwr;
printf("%d",bit);
highestfactor--;
i++;

}

system("pause");
getchar();
getchar();
return 0;
}```

2. Floating point numbers are not entirely trivial to print, but it certainly can be done.

The only difference when dealing with floating point numbers is that you have a fraction ("decimals" as you call it). The fraction is dealt with when you have done the integer section.

The fraction is sort of the opposite of the integer part, in that you MULTIPLY the fraction by the base, then take the integer part of that, and print it. Repeat until you either have sufficient decimal places or the number is zero.

--
Mats

3. well after the dot you have to multiply it by "lets say the number is 4.59 and you want to change it to base 2" you computation is;
4*2^0
5*2^-1
9*2^-2

how am I suppose to do the 5 and 9 ?? I already can do the ones before the dot but the part I want to know is the ones after the dot..

4. 4.59 is not a valid number in base 2.

If you have 4.59 in decimal and want to print it in binary, you would get 2^2 = 100. Then the fraction: 0.5 = 2^-1 = 0.1, leaving 0.09: 2^-4 = 0.0625, so 0.0001, leaving 0.0275. 2^-6 = 0.015625 = 0.000001, leaving 0.011875. So, so far we have 0.100101.

Another way to do that is:
0.59, multiply by 2. 1.18. Print 1.
*2 = 0.36 -> print 0
*2 = 0.72 -> print 0
*2 = 1.44 -> print 1
*2 = 0.88 -> print 0.
Etc. etc.

--
Mats

5. can you give me an simple example code if possible??

6. No [well, of coruse, I _CAN_ do that, in fact, I have previously posted a piece that does float to binary].

--
Mats

7. ok thanks..