C++打印取整

C++ printf Rounding?

本文关键字:打印 C++      更新时间:2023-10-16

我的代码:

   // 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("%fn", dVal);
  printf("%sn", std::to_string(dVal).data());

谷歌输出:0.01033468

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

调试器输出:0.01033468

printfstd::to_string是否取整?如何获得具有正确值的字符串?

字段宽度有点棘手

#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

std::to_string函数使用与printf:相同的符号

7,8)将浮点值转换为具有相同内容的字符串作为std::sprintf(buf, "%f", value)将产生的大buf。

printf文档显示:

Precision指定在小数点字符。默认精度为6。

您可以使用%.32f来指示您想要的小数位数(例如32):

printf("%.32fn", dVal);

我找不到用to_string更改小数位数的方法,但你可以用sprintf:将值打印到字符串中

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

如果你想要std::string:

std::string strVal(buffer);

感谢所有的回答,

这就成功了:

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

输出:

ss:0.01033468