C ++ printf舍入? [英] C++ printf Rounding?
本文介绍了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());
Google输出: 0.01033468
Google output: 0.01033468
程序输出: printf
和 std :: to_string
调试器输出: 0.01033468
Debugger output: 0.01033468
Do printf
和 std :: to_string
舍入数字?
如何获取一个具有合适值的字符串?
Do printf
and std::to_string
round the number?
How do I get a string with the proper value?
推荐答案
p>
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;
}
输出:
0.01033468
1000000.000033
这篇关于C ++ printf舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文