文章目录
float 精度和转换成str
- 控制float 进度
- 输出string
#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
uint32_t value_1 = 6458;
uint64_t value_2 = 127788;
float result = static_cast<float>(value_1) / static_cast<float>(value_2);
// Set precision to 3 decimal places
std::ostringstream ss;
ss << std::fixed << std::setprecision(3) << result;
std::string resultString = ss.str();
std::cout << "Result as string: " << resultString << std::endl;
return 0;
}
output:
Result as centesimal: 5.054%
- std::setprecision
在此示例中,使用 标头使用 std::setprecision(3) 将浮点值的精度设置为小数点后 3 位。 - std::fixed
使用 std::fixed 来确保小数位数是固定的而不是科学记数法。 - std::ostringstream
std::ostringstream 将格式化的浮点值转换为字符串 (resultString)。 - 调整
可以调整 std::set precision 参数来控制要保留的小数位数。同样,您可以将 resultString 的数据类型从 std::string 更改为适合您需要的任何类型(例如 const char* 等)。