C++打印取整
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("%fn", dVal);
printf("%sn", std::to_string(dVal).data());
谷歌输出:0.01033468
程序输出:printf
和std::to_string
均为0.010335
调试器输出:0.01033468
printf
和std::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
std::to_string
函数使用与printf
:相同的符号
7,8)将浮点值转换为具有相同内容的字符串作为
std::sprintf(buf, "%f", value)
将产生的大buf。
printf
文档显示:
Precision指定在小数点字符。默认精度为6。
您可以使用%.32f
来指示您想要的小数位数(例如32):
printf("%.32fn", dVal);
我找不到用to_string
更改小数位数的方法,但你可以用sprintf
:将值打印到字符串中
char buffer [100];
sprintf (buffer, "%.32f", dVal);
printf ("%sn",buffer);
如果你想要std::string
:
std::string strVal(buffer);
感谢所有的回答,
这就成功了:
std::stringstream ss;
ss << std::setprecision(8) << dVal;
std::string s = ss.str();
printf("ss: %sn", s.data());
输出:
ss:0.01033468
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数