控制字符串中浮点数的精度 - C ++

时间:2016-09-29 14:55:16

标签: c++ string floating-point precision

我正在尝试控制我在字符串中添加的数字的数量,但由于我正在打印一个字符串数组,因此我无法控制它。

0 errors
1 warning (...Conflicts between different versions of the same dependent assembly...) 
Build succeeded

但我最终得到一个看起来像这样的字符串数组:

  

0.050000 // 3.000000 //...

在将浮点数添加到字符串之前,有没有办法控制浮点数的精度?

(所以我可以得到一个结果字符串控制固定数量的数字)

  

0.05 // 3.00 // ...

2 个答案:

答案 0 :(得分:3)

declare @v int = 805; -- obviously in real code this would be a column select @v / 100 as [month], @v % 100 as [day] std::stringstreamstd::fixed一起使用。

Introduction to MongoDB in Node.js

答案 1 :(得分:1)

您可以使用标准流媒体机制:

您可以使用ostream生成字符串:

#include <ostream>
#include <sstream>
#include <iomanip>

std::ostringstream stream;
for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

我们的想法是生成一个可以流式传输字符串的流。然后,您可以使用std::string生成stream.str()。 Streams具有如何转换数字的默认值。您可以使用std::setprecisionstd::fixed以及其他变量来影响这一点(有关详细信息,请参阅C++ stdlib reference)。

使用std::setprecisionstd::fixed

std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;

for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

您会找到另一个示例here

的sprintf

你总是可以走C路并使用sprintf虽然不鼓励,因为你必须提供一个正确长度的缓冲区,例如:

char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
   std::string s(buf);
}
相关问题