std::to_string
doesn't support this, and in fact is not generally great for arbitrary floating-point values.
Since your question is tagged c++11, there are two ways I'm aware of. Firstly, you have std::stringstream
, which is type safe and will work with arbitrary types:
#include <sstream>
// ...
float number = 30.0f;
std::ostringstream oss;
oss << std::setprecision(1) << number;
std::string result = oss.str();
Alternatively, you have std::snprintf
, which requires converting through a char
buffer of a given size:
float number = 30.0f;
char buffer[20]; // maximum expected length of the float
std::snprintf(buffer, 20, "%.1f", number);
std::string str(buffer);
From C++17 you may use std::to_chars
instead in a similar way to std::snprintf
, and from C++20 you may use std::format
.