C ++ printf舍入?

小便

我的代码:

   // 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());

谷歌输出:0.01033468

程序输出:0.010335既为printfstd::to_string

调试器输出:0.01033468

难道printfstd::to_string轮数?如何获得具有正确值的字符串?

decltype_auto

字段宽度有点棘手

#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;
}

输出:

0.01033468
1000000.000033

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章