简体   繁体   中英

C++ printf Rounding?

My code:

   // Convert SATOSHIS to BITCOIN
    static double SATOSHI2BTC(const uint64_t& value)
    {
        return static_cast<double>(static_cast<double>(value)/static_cast<double>(100000000));
    }

    double dVal = CQuantUtils::SATOSHI2BTC(1033468);
    printf("%f\n", dVal);
  printf("%s\n", std::to_string(dVal).data());

Google output: 0.01033468

Program output: 0.010335 both for printf and std::to_string

Debugger output: 0.01033468

Do printf and std::to_string round the number? How do I get a string with the proper value?

The std::to_string function uses the same notation as with printf :

7,8) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%f", value) would produce for sufficiently large buf.

The printf documentation shows:

Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is 6.

You can use %.32f to indicate how many decimals you want (eg 32):

printf("%.32f\n", dVal);

I cannot find a way to change the number of decimals with to_string , but you could print the value to a string with sprintf :

char buffer [100];
sprintf (buffer, "%.32f", dVal);
printf ("%s\n",buffer);

And if you want a std::string :

std::string strVal(buffer);

It's a little tricky with the field width

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <sstream>
#include <limits>

#define INV_SCALE 100000000

static const int      WIDTH   = std::ceil(
                                    std::log10(std::numeric_limits<uint64_t>::max())
                                ) + 1 /* for the decimal dot */;
static const uint64_t INPUT   = 1033468;
static const double   DIVISOR = double(INV_SCALE);
static const int      PREC    = std::ceil(std::log10(DIVISOR));

static const double   DAVIDS_SAMPLE = 1000000.000033;

namespace {
std::string to_string(double d, int prec) {
    std::stringstream s;
    s << std::fixed
      << std::setw(WIDTH)
      << std::setprecision(prec) 
      << d;
    // find where the width padding ends    
    auto start = s.str().find_first_not_of(" ");
    // and trim it left on return
    return start != std::string::npos ? 
                    &(s.str().c_str()[start]) : "" ;
}
}

int main() {
    for (auto& s : 
            {to_string(INPUT/DIVISOR, PREC), to_string(DAVIDS_SAMPLE, 6)} 
        ) std::cout << s << std::endl;

    return /*EXIT_SUCCESS*/ 0;
}

output:

0.01033468
1000000.000033

Thanks to all answers,

this made the trick:

std::stringstream ss;
ss << std::setprecision(8) << dVal;
std::string s = ss.str();
printf("ss: %s\n", s.data());

Output:

ss: 0.01033468

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM