-1

I am trying to convert double precision number in C to char* array, but I cannot use methods such as sprintf or anything outside of stdlib library. I am trying to have a mathematical approach where I find the number of digits + dot sign and put each digit int the array, however it is really hard when precision is high, like 102.45555

Any ideas on how can this be achieved?

Mgetz
  • 5,108
  • 2
  • 33
  • 51
Damian
  • 461
  • 1
  • 7
  • 18

2 Answers2

1

You can go in this approach:

cast the double to an int, then store the digits of the int in the char array
append the decimal point
subtract the int from the double
while you don't have sufficient number of digits after decimal point:
    multiply the double by 10
    cast it to int and append it to the array
    subtract the int from the double
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
1

Alright here is how I would go about the approach:

First print out the integer part:

double value = 123.456
char buffer[50];
int bufferSize = 0;

int intPart = (int)value;
//find the size of the intPart by repeatedly dividing by 10
int tmp = intPart, size = 0;
while(tmp){
    size++;
    tmp /= 10;
}
//print out the numbers in reverse
for(int i = size-1; i >= 0; i--){
    buffer[i] = (intPart % 10) + '0';
    intPart /= 10;
}
bufferSize += size;

Now that you have printed out the integer part, its time to print out the decimal part. The way I would approach it would be to multiply it by ten until it is an integer.

value -= intPart;
while(floor(value) != value)
  value *= 10;

And now I would repeat the same process above:

intPart = (int)value;
//find the size of the intPart by repeatedly dividing by 10
tmp = intPart, size = 0;
while(tmp){
    size++;
    tmp /= 10;
}
//print out the numbers in reverse
for(int i = size-1; i >= 0; i--){
    buffer[bufferSize + i] = (intPart % 10) + '0';
    intPart /= 10;
}
bufferSize += size;

And finally the finishing touch:

buffer[bufferSize] = 0;
ASKASK
  • 657
  • 8
  • 16
  • Your foor loops need i-- instead because you are moving backwards. Good idea but doesnt work for huge decimals with 0s, such as 123.45600005 – Damian Mar 12 '14 at 13:44