双精度和字符串流格式 [英] double and stringstream formatting

查看:111
本文介绍了双精度和字符串流格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double val = 0.1;
std::stringstream ss;
ss << val;
std::string strVal= ss.str();

在Visual Studio调试器中, val 具有值0.10000000000000001(因为无法表示0.1)。
使用字符串流转换 val 时, strVal 等于 0.1 。但是,使用boost :: lexical_cast时,生成的 strVal 0.10000000000000001

In the Visual Studio debugger, val has the value 0.10000000000000001 (because 0.1 can't be represented). When val is converted using stringstream, strVal is equal to "0.1". However, when using boost::lexical_cast, the resulting strVal is "0.10000000000000001".

另一个示例如下:

double val = 12.12305000012;

在视觉工作室 val 下显示为12.123050000119999,并使用stringstream和默认精度(6)变为12.1231。我不太明白为什么不是12.12305(...)。

Under visual studio val appears as 12.123050000119999, and using stringstream and default precision (6) it becomes 12.1231. I don't really understand why it is not 12.12305(...).

是否存在默认精度,或者stringstream是否具有特定的算法来转换双精度值

Is there a default precision, or does stringstream have a particular algorithm to convert a double value which can't be exactly represented?

谢谢。

推荐答案

您可以如下更改 stringstream 的浮点精度:

You can change the floating-point precision of a stringstream as follows:

double num = 2.25149;
std::stringstream ss(stringstream::in | stringstream::out);
ss << std::setprecision(5) << num << endl;
ss << std::setprecision(4) << num << endl;

输出:

2.2515
2.251

请注意在适当的时候如何对数字进行四舍五入。

Note how the numbers are also rounded when appropriate.

这篇关于双精度和字符串流格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆