Pelles C forum

C language => Beginner questions => Topic started by: magic on September 22, 2008, 10:27:56 PM

Title: convert double to string to double
Post by: magic on September 22, 2008, 10:27:56 PM
Is there a preset library to
convert from double to string and
convert from string to double
Title: Re: convert double to string to double
Post by: Stefan Pendl on September 23, 2008, 09:09:58 AM
You would use sprintf to convert from a number to a string and any of the ato... or strto... functions to convert from string to number.
Title: Re: convert double to string to double
Post by: magic on October 24, 2008, 06:10:59 AM
could you give me sample how to  use sprintf(). The documentation is quite difficult for me to understand without sample.
Say, I want to convert a double number into a string.:

        double myDOUBLE=123.456;
char* mySTRING=GlobalAlloc(GMEM_FIXED,64);     //alocate string in memory
_strnset(mySTRING,0,1);                                   //initilize mySTRINGto ""
int sprintf(testing,myDOUBLE%???);                     //I can't really understand how to format it


Title: Re: convert double to string to double
Post by: Robert on October 24, 2008, 06:56:45 AM
Here are two examples

Example 1


#include <windows.h>
#include <stdio.h>

int main(void) {
  double myDOUBLE=123.456;
  char* mySTRING=GlobalAlloc(GMEM_FIXED,64);     //allocate string in memory
  _strnset(mySTRING,0,1);                        //initilize mySTRINGto ""
  int i;
 
  i = sprintf(mySTRING, "%G", myDOUBLE);
  printf("123.456 as a string is %s\n", mySTRING);
  printf("sprintf returns: %d\n\n", i);

  return 0;
}



Example 2



#include <stdio.h>

int main(void) {
  double dub1 = 123.456;
  char str1[10];
  int i;
 
  i = sprintf(str1, "%G", dub1);
  printf("123.456 as a string is %s\n", str1);
  printf("sprintf returns: %d\n\n", i);

  return 0;
}



I hope this helps.

Robert Wishlaw