string保留小数点后2位
时间: 2023-09-07 18:16:52 浏览: 72
你可以使用以下方法来保留小数点后两位:
1. 使用 C++ 的 iomanip 库:
```c++
#include <iostream>
#include <iomanip>
#include <string>
int main() {
double number = 3.14159;
std::string result = std::to_string(number);
size_t pos = result.find('.');
if (pos != std::string::npos && result.size() > pos + 2) {
result = result.substr(0, pos + 3);
}
std::cout << result << std::endl;
return 0;
}
```
2. 使用 C 的 sprintf 函数:
```c++
#include <stdio.h>
int main() {
double number = 3.14159;
char result[10];
sprintf(result, "%.2lf", number);
printf("%s\n", result);
return 0;
}
```
这些方法将会输出 "3.14",保留了小数点后两位。你可以将 number 替换为你需要处理的实际数字。
相关问题
string截取小数点后两位
你可以使用以下代码来截取一个浮点数的小数点后两位:
```
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
string str = "3.14159265359";
stringstream stream(str);
double num;
stream >> num;
stringstream result;
result << fixed << setprecision(2) << num;
string output = result.str().substr(0, result.str().size()-1);
cout << output << endl;
return 0;
}
```
这段代码会将字符串 "3.14159265359" 转换成一个浮点数,然后使用 `std::fixed` 和 `std::setprecision(2)` 来保留小数点后两位,最后使用 `std::substr` 来截取字符串中小数点前的部分和小数点后两位。输出结果为 "3.14"。
Java保留小数点后2位
在Java中保留小数点后2位有几种方法:
1. 使用DecimalFormat类
DecimalFormat类可以将数字格式化为指定格式的字符串,例如保留小数点后2位可以使用“0.00”作为格式化字符串。
示例代码:
```java
double num = 3.1415926;
DecimalFormat df = new DecimalFormat("0.00");
String result = df.format(num);
System.out.println(result); // 输出3.14
```
2. 使用String.format()方法
String类的format()方法可以将字符串格式化为指定格式的字符串,其中“%.2f”表示保留小数点后2位。
示例代码:
```java
double num = 3.1415926;
String result = String.format("%.2f", num);
System.out.println(result); // 输出3.14
```
3. 使用Math.round()方法
Math.round()方法可以将小数点后第3位四舍五入,然后再除以100得到保留小数点后2位的结果。
示例代码:
```java
double num = 3.1415926;
double result = Math.round(num * 100) / 100.0;
System.out.println(result); // 输出3.14
```