使用ostringstream将double格式化为字符串
Formatting double to string with ostringstream
我想将双精度转换为字符串,四舍五入到小数点后的2位。我希望1.009表示为"1.01",1.0表示为"1"。这就是我尝试过的:
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << std::noshowpoint << 1.0;
它输出"1.00",尽管我从未设置宽度,甚至指定了std::noshowpoint
。如何实现所需的表现?
最佳解决方案:
inline double twodec(double n) { return floor(n * 100 + 0.5) / 100; }
oss << twodec(1.0) << ' ' << twodec(1.009);
讨论
发件人http://www.cplusplus.com/reference/ios/fixed/(我的斜体字)
当floatfield设置为固定时,使用定点表示法写入浮点值,这意味着该值用表示,小数部分的位数与精度字段指定的位数完全相同,并且没有指数部分。
所以,"固定"是行不通的。
也就是说,我能想到的做你想做的事的唯一方法是:
- 先将数字四舍五入到所需的精度(即
floor(n * 100 + 0.5) / 100
),然后使用默认表示形式(即不要指定固定的、科学的或精度-如果fixed
或scientific
有效,请先用std::cout.unsetf(std::ios::floatfield)
清除它们) - 根据点前后要查看的最大数字总数动态设置精度(这是精度指定的值);要做到这一点,您可以计算出小数点之前的部分需要多少位数(可能使用10为基数),然后加2
- 将结果流式传输到
ostringstream
,然后删除后面的0和任何"."(相当可怕)
这是我基于Tony答案的最终解决方案:
template <typename T>
std::string stringForNumber( T f, int precision /* = 0 */, bool fixedWidth /*= false*/ )
{
std::ostringstream ss;
ss.setf(std::ios_base::fixed);
if (precision > 0)
ss << std::setprecision(precision);
ss << f;
std::string str(ss.str());
if (!fixedWidth) // Removing trailing 0
{
const auto pointLocation = str.find_first_of(".,");
if (pointLocation != std::string::npos)
{
const auto lastZeroPos = str.find_last_of('0');
const auto lastNotZeroPos = str.find_last_not_of('0');
if (lastNotZeroPos == pointLocation) // Integer number
str.erase(pointLocation);
else if (lastZeroPos != std::string::npos && lastNotZeroPos != std::string::npos && pointLocation < lastZeroPos && lastNotZeroPos < lastZeroPos)
{
str.erase(lastNotZeroPos+1);
}
}
}
return str;
}
相关文章:
- 如何从C++中的格式化字符串派生整数?
- C++逐步格式化字符串
- C++:格式化包含十六进制值的字符串
- 格式化返回字符串C++
- 有没有更快的方法从成员函数返回格式化字符串
- 如何在C++中对静态缓冲区执行字符串格式化?
- 格式化的时间字符串在解析为time_point时会产生小时差异
- C++ ctime() 迄今为止格式化的字符串?
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 如何在提升库中格式化字符串
- 使用参数的可变大小向量格式化字符串(例如,将参数向量传递给 std::snprintf)
- 使用 c++ 格式化字符串的自然方法
- 使用此字符串重新格式化器使用什么代替 substr
- snprintf等效于WCHAR_T计算格式化的字符串大小(MAC)
- WXSTRING:是否有使用类似Python3的占位符实现字符串格式化的C/C 代码
- C字符串.格式化插入斜杠
- 如何截断字符串 [格式化] ?C++
- 是否为osx标准库实现swscanf子字符串格式化([a-z])
- c++字符串格式化-固定宽度的浮点数,以及在偏移处有空格的字符串
- 如何创建可变模板字符串格式化程序