我试图在C++小数点之后打印最多4位数字(使用流)。所以,如果这个数字不需要小数点之后的4位,我希望它只使用它实际需要的小数数。
示例:
1.12345 -> 1.1234
1.0 -> 1
1.12 -> 1.12
1.12345789 -> 1.1234
123.123 -> 123.123
123.123456 -> 123.1234我尝试了std::setprecision(4),但是这设置了有效数字的数量,但是在测试用例中失败了:
123.123456 gives 123.1我还尝试将std::fixed与std::setprecision(4)一起给出,但这在小数点之后给出了一个固定的数字,即使不需要:
1.0 gives 1.0000std::defaultfloat似乎是我所需要的,不是固定的,也不是指数的。但是它似乎没有适当地打印十进制后的数字数,并且只有一个重要数字的选项。
发布于 2016-12-19 20:31:51
我们可以使用std::stringstream和std::string来实现这一点。我们将double传递给流,将其格式化,就像将它发送到cout一样。然后,我们检查从流中得到的字符串,看看是否有尾随零。如果有,我们就除掉他们。一旦我们这样做,我们检查是否只剩下小数点,如果我们是,那么我们也摆脱了它。你可以用这样的东西:
int main()
{
double values[] = { 1.12345, 1.0, 1.12, 1.12345789, 123.123, 123.123456, 123456789, 123.001 };
std::vector<std::string> converted;
for (auto e : values)
{
std::stringstream ss;
ss << std::fixed << std::setprecision(4) << e;
std::string value(ss.str());
if (value.find(".") != std::string::npos)
{
// erase trailing zeros
while (value.back() == '0')
value.erase(value.end() - 1);
// if we are left with a . at the end then get rid of it
if (value.back() == '.')
value.erase(value.end() - 1);
converted.push_back(value);
}
else
converted.push_back(value);
}
for (const auto& e : converted)
std::cout << e << "\n";
}当被制作成运行示例时
1.1235
1
1.12
1.1235
123.123
123.1235
123456789
123.001发布于 2016-12-19 20:34:44
使用来自这里的答案和自定义逻辑移除零和点:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
std::string remove_zeros(std::string numberstring)
{
auto it = numberstring.end() - 1;
while(*it == '0') {
numberstring.erase(it);
it = numberstring.end() - 1;
}
if(*it == '.') numberstring.erase(it);
return numberstring;
}
std::string convert(float number)
{
std::stringstream ss{};
ss << std::setprecision(4) << std::fixed << std::showpoint << number;
std::string numberstring{ss.str()};
return remove_zeros(numberstring);
}
int main()
{
const float values[]{1.12345, 1.0, 1.12, 1.12345789, 147323.123, 123.123456};
for(auto i : values)
std::cout << convert(i) << '\n';
}生产:
1.1235
1
1.12
1.1235
147323.125
123.1235https://stackoverflow.com/questions/41229910
复制相似问题