gpt4 book ai didi

C++11 std::to_string(double) - 没有尾随零

转载 作者:IT老高 更新时间:2023-10-28 13:58:26 34 4
gpt4 key购买 nike

今天试用了C++11 STL的一些新功能,遇到了std::to_string

可爱,可爱的一组功能。为一个双字符串转换创建一个字符串流对象对我来说总是有点过头了,所以我很高兴我们现在可以做这样的事情:

std::cout << std::to_string(0.33) << std::endl;

结果?

0.330000

我对此并不完全满意。有没有办法告诉 std::to_string 省略尾随零?我搜索了互联网,但据我所知,该函数只接受一个参数(要转换的值)。回到使用字符串流的“过去”,您可以设置流的宽度,但我宁愿不转换回来。

之前有人遇到过这个问题/有解决方案吗?一些 StackOverflow 搜索结果一无所获。

(C++11 STL 引用:http://en.cppreference.com/w/cpp/string/basic_string/to_string)

最佳答案

如果您只想删除尾随零,那很简单。

std::string str = std::to_string (f);
str.erase ( str.find_last_not_of('0') + 1, std::string::npos );
str.erase ( str.find_last_not_of('.') + 1, std::string::npos );

关于C++11 std::to_string(double) - 没有尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686482/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com