Last active
August 24, 2016 13:33
-
-
Save mbasaglia/14f06fb4870f63bdc8505f7594d763a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cmath> | |
#include <limits> | |
#include <iostream> | |
#include "melanolib/math/math.hpp" | |
using namespace melanolib; | |
template<class Float> | |
std::string float_to_string(Float value) | |
{ | |
if ( std::isnan(value) ) | |
return "NaN"; | |
if ( std::isinf(value) ) | |
{ | |
if ( value < 0 ) | |
return "-Inf"; | |
else | |
return "Inf"; | |
} | |
static const int base = 10; | |
int k = math::ceil(math::log(value, base)); | |
std::string digits; | |
Float q = value / math::pow(base, k); | |
for ( int i = 0; i < 10; i++ ) | |
{ | |
Float scaled = q * base; | |
int digit = math::floor(scaled); | |
q = scaled - digit; | |
digits += '0' + digit; | |
} | |
int next_digit = math::floor(q * base); | |
if ( next_digit >= 5 ) | |
{ | |
for ( auto it = digits.rbegin(); it != digits.rend(); ++it ) | |
{ | |
*it += 1; | |
if ( *it > '9' ) | |
*it = '0'; | |
else | |
break; | |
} | |
} | |
return "0." + digits + "e" + std::to_string(k); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment