Skip to content

Instantly share code, notes, and snippets.

@mbasaglia
Last active August 24, 2016 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbasaglia/14f06fb4870f63bdc8505f7594d763a4 to your computer and use it in GitHub Desktop.
Save mbasaglia/14f06fb4870f63bdc8505f7594d763a4 to your computer and use it in GitHub Desktop.
#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