This little C program converts a decimal value — represented as a string — into a double-precision floating-point number:
#include <string.h> int main (void) { double intPart = 0, fracPart = 0, conversion; unsigned int i; char decimal[] = "3.14159"; i = 0; /* Left to right */ while (decimal[i] != '.') { intPart = intPart*10 + (decimal[i] - '0'); i++; } i = strlen(decimal)-1; /* Right to left */ while (decimal[i] != '.') { fracPart = (fracPart + (decimal[i] - '0'))/10; i--; } conversion = intPart + fracPart; }
The conversion is done using the elegant Horner’s method, summing each digit according to its decimal place value. So why do I call it “quick and dirty?” Because the binary floating-point value it produces is not necessarily the closest approximation to the input decimal value — the so-called correctly rounded result. (Remember that most real numbers cannot be represented exactly in floating-point.) Most of the time it will produce the correctly rounded result, but sometimes it won’t — the result will be off in its least significant bit(s). There’s just not enough precision in floating-point to guarantee the result is correct every time.
I will demonstrate this program with different input values, some of which convert correctly, and some of which don’t. In the end, you’ll appreciate one reason why library functions like strtod() exist — to perform efficient, correctly rounded conversion.
Continue reading “Quick and Dirty Decimal to Floating-Point Conversion”