c++将float型转为string型
时间: 2023-10-14 15:31:23 浏览: 52
在C++中,可以使用标准库函数`std::to_string()`将`float`类型转换为`std::string`类型。例如:
```c++
float a = 3.14;
std::string str = std::to_string(a);
```
这样,变量`str`就是`"3.140000"`。需要注意的是,`std::to_string()`会保留6位小数,如果需要更多或更少的小数位数,可以使用`std::stringstream`配合格式化输出实现。例如:
```c++
#include <sstream>
#include <iomanip>
float a = 3.1415926;
std::stringstream ss;
ss << std::setprecision(8) << a;
std::string str = ss.str();
```
这样,变量`str`就是`"3.1415926"`,保留了8位小数。
相关问题
c++ 将float转为字符串
在C++中,有多种方法可以将float类型转换为string类型。以下是其中的三种方法:
方法一:
```c++
#include <sstream>
std::string Convert(float Num) {
std::ostringstream oss;
oss << Num;
std::string str(oss.str());
return str;
}
```
方法二:
```c++
#include <sstream>
int main(){
float num = 10.11;
std::string data = std::to_string(num);
printf("data: %s\n", data.c_str());
return 0;
}
```
方法三:
```c++
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace std;
string FloatToString(float f) {
char buf[32];
sprintf(buf, "%.2f", f);
return string(buf);
}
```
以上三种方法都可以将float类型转换为string类型,具体使用哪种方法取决于你的需求和个人喜好。
C++ string转为float
可以使用atof函数将C字符串转换为float类型。
例如:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14";
float num = atof(str);
printf("The float number is %.2f\n", num);
return 0;
}
```
输出结果为:
```
The float number is 3.14
```