2015-11-02 50 views
2

我的代碼: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整數? 如何獲得正確值的字符串?

+0

爲'to_string()'和(我猜'printf')的默認精度爲6位小數(看到這一點:http://stackoverflow.com/questions/14520309/the-precision-of-stdto-stringdouble和http:// stackoverflow。com/questions/16605967/set-precision-of-stdto-string-when-conversion-floating-point-values) – Nim

+1

「google」(wtf?)和調試器輸出都沒有任何意義。 –

+0

對不起,錯誤的複製/粘貼。更新。 如果您使用Google Calc,Google輸出就是您所得到的結果。 感謝您的回答@Nim – PeeS

回答

1

這是與一個小技巧字段寬度

#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 
+0

這只是瘋了......, 我不能弄清楚。 尊重。 – PeeS

+0

只是一個草圖;這太昂貴了,不具有普遍性。但它應該是你的訣竅。 –

1

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); 
-1

感謝所有的答案,

本作的伎倆:

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

輸出:

SS:0.01033468

+0

這不起作用。嘗試使用'1000000.000033'的dVal。甚至只是[this](http://codepad.org/SZKzKC4z)。 –

+0

不可思議..那麼如何處理呢? – PeeS

+0

不要使用「雙」。爲什麼你會用這個'double'?這絕對沒有意義。你想將一個整數轉換爲一個字符串,爲什麼要通過其他數字類型?這是堅果。 –