This routine is called a zillion times to create large csv files full of numbers. Is there a more efficient way to to this?
static std::string dbl2str(double d)
{
std::stringstream ss;
ss << std::fixed << std::setprecision(10) << d; //convert double to string w fixed notation, hi precision
std::string s = ss.str(); //output to std::string
s.erase(s.find_last_not_of('0') + 1, std::string::npos); //remove trailing 000s (123.1200 => 123.12, 123.000 => 123.)
return (s[s.size()-1] == '.') ? s.substr(0, s.size()-1) : s; //remove dangling decimal (123. => 123)
}
6. Trailing zeros in a whole number with no decimal shown are NOT significant. Writing just "540" indicates that the zero is NOT significant, and there are only TWO significant figures in this value.
One of the trickiest things about scientific notation is remembering the rules for zeros: if a number ends in one or more zeros, do not include the zeros if the number is a whole number, but do include the zeros if the number is a decimal.
A trailing zero is a zero digit in the representation of a number which has no non-zero digits that are less significant than the zero digit. Put more simply, it is a zero digit with no non-zero digits to the right of it.
Use a string literal to suppress scientific notation Use the string literal syntax f"{num:. nf}" to represent num in decimal format with n places following the decimal point.
Efficient in terms of speed or brevity?
char buf[64];
sprintf(buf, "%-.*G", 16, 1.0);
cout << buf << endl;
Displays "1". Formats up to significant 16 digits, with no trailing zeros, before reverting to scientific notation.
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