Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double to string without scientific notation or trailing zeros, efficiently

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)
    }
like image 439
tpascale Avatar asked Mar 01 '13 19:03

tpascale


People also ask

Why are trailing zeros not significant if there is no decimal point?

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.

Do you keep trailing zeros in scientific notation?

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.

What does no trailing zero mean?

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.

How do you turn off scientific notation in Java?

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.


1 Answers

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.

like image 193
BSalita Avatar answered Sep 20 '22 11:09

BSalita