删除尾随零 - c++
Removing trailing zeros - c++
此代码:
cout<< to_string(x) + "m ----> " + to_string(x *0.001)+ "km"<<endl;
使用此输出:0.002000
但是,我想删除尾随的额外零,但它应该在一行代码中,因为我有很多像上面这样的行。
试试这个狙击手:
cout << "test zeros" << endl;
double x = 200;
cout << "before" << endl;
cout<< std::to_string(x) + "m ----> " + std::to_string(x *0.001)+ "km"<<endl;
std::string str = std::to_string(x * 0.001);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
cout << "after" << endl;
cout<< std::to_string(x) + "m ----> " + str + "km"<<endl;
带输出:
test zeros
before
200.000000m ----> 0.200000km
after
200.000000m ----> 0.2km
然后更好std::setprecision
因为您不需要决定要保留多少 num,而是让实现为您找到它。
此处的文档提供了一些额外信息。
尝试使用std::setprecsion()
设置小数精度
设置用于设置输出操作浮点值格式的小数精度。
因此,在您的情况下,您可以使用:
std::cout << std::setprecision(3)
这将删除从 0.0020000 到 0.002 的尾随零
编辑
当您想在代码中使用to_string时,以下代码有效:
#include <iostream>
using namespace std;
int main(){
int x=1;
string str2 = to_string(x *0.001);
str2.erase ( str2.find_last_not_of('0') + 1, std::string::npos );;
std::cout<<to_string(x)+ "m ----> " + str2+ "km";
}
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 如何从存储在std::映射中的std::集中删除元素
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数