C++float转string保留两位小数
时间: 2023-09-04 21:17:22 浏览: 98
你可以使用 `std::stringstream` 类来将浮点数转换为字符串并保留指定的小数位数。以下是一个示例代码:
```c++
#include <iostream>
#include <sstream>
#include <iomanip> // for std::setprecision() and std::fixed
int main() {
float num = 3.14159;
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << num;
std::string str = ss.str();
std::cout << str << std::endl; // "3.14"
return 0;
}
```
在上面的代码中,我们使用 `std::fixed` 来指定使用固定小数位数(不使用科学计数法),使用 `std::setprecision(2)` 来指定保留两位小数,最后使用 `ss.str()` 将流中的内容转换为字符串。
相关问题
float转为string保留两位小数 C++
你可以使用C++中的stringstream来将float转换为string并保留两位小数。以下是示例代码:
```c++
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
int main() {
float f = 3.14159;
stringstream s;
s << fixed << setprecision(2) << f;
string result = s.str();
cout << result << endl;
return 0;
}
```
在上面的示例中,我们使用了`fixed`和`setprecision`函数来保留两位小数,并将结果存储在stringstream对象`s`中。最后,我们使用`s.str()`函数将结果转换为string类型并打印出来。
float 转为string保留两位小数 C++
可以使用以下代码将 float 转为 string 并保留两位小数:
```c++
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main() {
float num = 3.14159;
std::ostringstream stream;
stream << std::fixed << std::setprecision(2) << num;
std::string str_num = stream.str();
std::cout << str_num << std::endl; // 输出 3.14
return 0;
}
```
这里使用了 ostringstream 类来将 float 类型的变量 num 转换为 string 类型的变量 str_num。std::fixed 表示将浮点数转换为定点数格式,std::setprecision(2) 表示保留两位小数。最后用 stream.str() 获取转换后的字符串。