gpt4 book ai didi

C++ printf 舍入?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:02 26 4
gpt4 key购买 nike

我的代码:

   // 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 输出:0.01033468

程序输出:0.010335 printfstd::to_string

调试器输出: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

关于C++ printf 舍入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33477602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com