0

I want to remove trailing zeros from doubles whilst they're being converted to a string. For example, 0.9345750000 => 0.934575 and 0.6 => 0.6

I'm currently using this:

std::stringstream ss;
ss << std::setprecision(15) << std::noshowpoint << value;
std::string num = ss.str();

but it's converting 0.00001 to 1e-05.

So, I added std::fixed:

std::stringstream ss;
ss << std::fixed << std::setprecision(15) << std::noshowpoint << value;
std::string num = ss.str();

but now 0.9345750000 appears as 0.9345750000, i.e. the trailing zeros haven't been removed.

How can I convert a double to string, regardless of how many decimal places it has, prevent scientific notation, whilst still removing trailing zeros?

intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • Will it help? https://stackoverflow.com/a/18882414/8510613 – user8510613 Aug 08 '22 at 03:47
  • Just search for the decimal point, and if you find one, walk backwards to that point from the end of the string until you encounter a non-zero. Then truncate the string to end on that character. If you reach the decimal point, jump back one more. Be careful though, because if you don't imbue your stringstream with a known locale, your decimal point might be something else (_e.g._ a comma) on some systems. Alternatively, you can query the current locale to determine the decimal separator character. – paddy Aug 08 '22 at 04:18

0 Answers0