If you want to convert to fixed decimal numbers (for example, release the +/- "E" part), then this will greatly facilitate the execution:
#include <stdio.h> #include <cstring> // strcpy #include <iostream> // std::cout, std::fixed #include <iomanip> // std::setprecision #include <new> char *ToDecimal(double val, int maxChars) { std::ostringstream buffer; buffer << std::fixed << std::setprecision(maxChars-2) << val; std::string result = buffer.str(); size_t i = result.find_last_not_of('\0'); if (i > maxChars) i = maxChars; if (result[i] != '.') ++i; result.erase(i); char *doubleStr = new char[result.length() + 1]; strcpy(doubleStr, (const char*)result.c_str()); return doubleStr; } int main() { std::cout << ToDecimal(1.26743237e+015, 8) << std::endl; std::cout << ToDecimal(-1.0, 8) << std::endl; std::cout << ToDecimal(3.40282347e+38, 8) << std::endl; std::cout << ToDecimal(1.17549435e-38, 8) << std::endl; std::cout << ToDecimal(-1E4, 8) << std::endl; std::cout << ToDecimal(12.78e-2, 8) << std::endl; }
Output:
12674323 -1 34028234 0.000000 -10000 0.127800
user152949
source share