remove trailing zeros within the middle of scientific representation

Viewed 43

I need to format a double in a specific way for a checksum.

0.000045 -> "4.5e-05"

0.0000632 -> "6.32e-05"

I tried this:

#include <sstream>

std::stringstream ss;
ss << std::scientific << std::showpoint << value;
return ss.str();

but I get lots of zeros following the decimal point:

"4.500000e-05"

Setting the precision does help:

std::stringstream ss;
ss << std::scientific << std::setprecision(3) << std::showpoint << value;
return ss.str();

Output:

"4.500e-05"

but I can't set the precision because it depends on the input number.

1 Answers

This should work for small numbers.

std::stringstream ss;
// Resets fixed and set scientific style.
ss.setf(std::ios_base::scientific | std::ios_base::showpoint, std::ios_base::fixed);
ss << value;
return ss.str();  // 4.5e-05 or 6.32e-05
Related