I am using std::to_string function to convert float to string.
float number = 30.0f; // this number will vary
when i convert the float number to string
std::to_string(number);
the std::cout shows the result as 30.000000
i want the result as 30.0 and remove the extra zeros.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With