On machine 12.341 results in “12.340999″. Close enough eh? Once I get this perfect, I’ll make it into a template function with specifications for making the string in ‘e’ notation.
#include <iostream>
#include <string>
#include <cmath>
#include <cstdio>
std::string ftos(float f, int precis = 6) {
int e, i;
std::string buf;
int whole;
bool neg;
/* Check for nan or [-]inf */
if (isnan(f)) return std::string("nan");
else if (e = isinf(f)) {
if (e < 0) return std::string("-inf");
else return std::string("inf");
}
/* Check for negative and convert to positive */
if (f < 0) { neg = true; f *= -1.0; }
/* Extract whole number */
for (whole = 0; f >= 1.0; f -= 1.0, whole++);
/* Convert whole number to string */
if (neg) buf.push_back('-');
char tmp[64];
sprintf(tmp, "%d", whole);
buf.append(tmp);
if (f == 0.0) return buf;
buf.push_back('.');
/* Loop through each floating digit in precision */
for (i = 0; i < precis; i++) {
if (f == 0.0) break;
/* Shift next floating digit to whole number */
f *= 10.0;
/* Extract whole number */
for (whole = 0; f >= 1.0; f -= 1.0, whole++);
/* Convert to character */
buf.push_back(whole + '0');
}
/* Fill with leading 0's for precision */
if (f == 0.0 && i < precis)
for (; i < precis; i++)
buf.push_back('0');
return buf;
}
int main() {
std::cout << ftos(12.341) << std::endl;
}