5

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Summit
  • 2,112
  • 2
  • 12
  • 36
  • 2
    See https://en.cppreference.com/w/cpp/string/basic_string/to_string .. note that to_string does not have support for this use-case. (The link hints at a suitable replacement function.) – user2864740 Jan 20 '20 at 04:42
  • Does this answer your question? [The precision of std::to\_string(double)](https://stackoverflow.com/questions/14520309/the-precision-of-stdto-stringdouble) – VLL Jan 20 '20 at 06:39

2 Answers2

10

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.

N. Shead
  • 3,828
  • 1
  • 16
  • 22
0

As per the documentation

With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero

However you can set the precision as stated in this The precision of std::to_string(double)

Paul
  • 448
  • 1
  • 6
  • 14
  • 2
    The conclusion of this answer implies (in part through title of the linked question) that one can set the to_string precision, which is incorrect. – user2864740 Jan 21 '20 at 00:24