2015-11-02 55 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'?这绝对没有意义。你想将一个整数转换为一个字符串,为什么要通过其他数字类型?这是坚果。 –