簡體   English   中英

C++ printf 四舍五入?

[英]C++ printf Rounding?

我的代碼:

   // 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

程序輸出: printfstd::to_string均為0.010335

調試器輸出: 0.01033468

printfstd::to_string對數字進行四舍五入? 如何獲得具有正確值的字符串?

std::to_string函數使用與printf相同的符號:

7,8) 將浮點值轉換為與std::sprintf(buf, "%f", value)為足夠大的 buf 產生的內容相同的字符串。

printf文檔顯示:

精度指定小數點字符后出現的最小位數。 默認精度為 6。

您可以使用%.32f來表示您想要的小數位數(例如 32):

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

我找不到使用to_string更改小數位數的方法,但您可以使用sprintf將值打印到字符串:

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

如果你想要一個std::string

std::string strVal(buffer);

字段寬度有點棘手

#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::stringstream ss;
ss << std::setprecision(8) << dVal;
std::string s = ss.str();
printf("ss: %s\n", s.data());

輸出:

SS:0.01033468

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM