WILD ARTIST All about LIFE

14Jan/10

Simple C++ function to convert number to string

I've used a function which converts numeric value into string and I want to show you the method here. First, there is a function converting integer to string (character array allocated in heap area).

static char* ConvertIntToString(const int num) {
// determine the sign and the number of chars
int abs_n = abs(num);
int sign = (num < 0) ? 1 : 0;
int length = (num != 0) ? (int)log10((double)abs_n) + 1 : 1;

// assign character array and initialize
char* converted = new char[length + sign + 1];
memset(converted, 0, (length + sign + 1) * sizeof(char));

// copy string from characteristic integer
int remainder = abs_n;
for(int i = 0; i < length + sign; i++) {
converted[length + sign - i - 1] = (remainder % 10) + '0';
remainder = (int)(remainder / 10);
}
if(sign > 0) converted[0] = '-';
return converted;
}

Moreover, a function converting double to string which is more complex than the previous thing is also available.

static char* ConvertDoubleToString(const double num, const int radix) {
// divide double number into characteristic and mantissan
double abs_n = abs(num);
int sign = (num < 0) ? 1 : 0;
int characteristic = (int)abs_n;
double mantissan = abs_n - characteristic;

// calculate each cipher for characteristic and mantissan
int length_char = (characteristic != 0) ? (int)log10((double)characteristic) + 1 : 1;
int length_mant = 0;
double remainder_mant = mantissan;
while(remainder_mant > 0) {
int chars_mant = (int)(remainder_mant * 10);
remainder_mant = (remainder_mant * 10) - chars_mant;
length_mant++;
if(length_mant >= radix) break;
}
if(length_mant == 0) length_mant = 1;

// assign character array and initialize
char* converted = new char[length_char + length_mant + sign + 2];
memset(converted, 0, (length_char + length_mant + sign + 2) * sizeof(char));

// copy string from characteristic integer
int remainder_char = characteristic;
for(int i = 0; i < length_char; i++) {
converted[length_char + sign - i - 1] = (remainder_char % 10) + '0';
remainder_char = (int)(remainder_char / 10);
}
converted[length_char+sign] = '.';

// copy string from mantissan
remainder_mant = mantissan;
for(int i = 0; i < length_mant; i++) {
int chars_mant = (int)(remainder_mant * 10);
remainder_mant = (remainder_mant * 10) - chars_mant;
converted[length_char + sign + i + 1] = chars_mant + '0';
}
if(sign > 0) converted[0] = '-';
return converted;
}

I heard of functions which convert string type value to number, but never for the opposite conversion. I'm not sure that they're optimized properly but it's very useful for me at least. Hopefully, it would be a little help for your project. Cheers!