Skip to content

Instantly share code, notes, and snippets.

@alinush
Created July 14, 2013 23:50
Show Gist options
  • Save alinush/5996610 to your computer and use it in GitHub Desktop.
Save alinush/5996610 to your computer and use it in GitHub Desktop.
Convert a double variable to a string
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
TCHAR * DoubleToString (TCHAR * buffer, double value, unsigned int precision)
{
// 'i' is going to be the current index into the buffer
unsigned int i = 0, j = 0, nDigits = 0;
unsigned long integer;
// First check the sign of the number
if (value < 0.0) {
value *= -1.0;
buffer[i++] = '-';
}
// Then take care of the integer part of the number
integer = (unsigned long)value;
// Count how many digits the integer part has
do
{
nDigits++;
integer /= 10;
} while (integer);
// Get back the integer part because we just messed with it when we got the number of digits above
integer = (unsigned long)value;
// Substract the integer part from the number so that we'll be left with the decimal part
value -= (double)integer;
j = nDigits;
do {
// Now copy each digit from the integer part into the string buffer
buffer[i+nDigits-1] = '0' + (integer%10);
integer /=10;
nDigits--;
} while(integer);
// Keep track of where the current index in the string buffer is after adding the digits
i += j;
// Add the decimal point
buffer[i++] = '.';
// Then take care of the real part
// Basically we're going to multiply the real part by 10, which gives us a number like x.yzw (because the real part was 0.xyzw)
// We then cast that number to an integer, which gives us 'x', and we then append that to the buffer.
// After that we substract the 'x' from x.yzw and we're left with 0.yzw
// We then repeat, decrementing the precision variable so that we can stop after 'precision' decimals.
while (precision)
{
value *= 10.0;
buffer[i++] = '0' + (unsigned int)value;
value -= (double)(unsigned long)value;
precision--;
}
// Null terminate the buffer and return it
buffer[i] = 0;
return buffer;
}
int main ()
{
double value = 23.4119;
TCHAR buffer[32];
unsigned int precision = 5;
_tprintf (TEXT("sizeof(TCHAR) is %d\n"), sizeof(TCHAR));
MessageBox (0, DoubleToString (buffer, value, precision), TEXT("Value"), MB_ICONINFORMATION);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment