Summit
Summit

Reputation: 2268

How to use std::to_string function to format float as “x.0”

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.

Upvotes: 6

Views: 11544

Answers (1)

N. Shead
N. Shead

Reputation: 3938

std::to_string doesn't support this, and in fact is not generally great for arbitrary floating-point values.

Since your question is tagged , 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.

Upvotes: 11

Related Questions