How do I elegantly format a string in C ++ so that it rounds to six decimal places and has an extra "0" or "9"

How do I write a function that formats a string with decimal digits, without ending 0s or unnecessary 9s? Given that the numeric value is 2, this is what I expect:

0.999 -> 1.0
0.99 -> 0.99
1.01 -> 1.01
1.001 -> 1.0
123 -> 123.0
0 -> 0.0
0.1 -> 0.1

      

(negatives as you would expect)

Here is what I have so far, but this is pretty ugly code. Is there a better way to do this?

string toStrMaxDecimals(double value, uint decimals) {
    value *= pow(10, decimals);
    value = round(value);
    value *= pow(0.1, decimals);
    string temp = boost::lexical_cast<string>(value); 
    size_t dot = temp.find('.');
    if (dot != string::npos) {
        if (temp.size() > dot + decimals + 1)
            temp.erase(dot + decimals + 1);
        if (*temp.rbegin() == '0')
            temp.erase(temp.find_last_not_of("0") + 1);
        if (*temp.rbegin() == '.')
            temp.append("0");
    } else {
        temp.append(".0");
    }
    return temp;
}

      

+1


a source to share


3 answers


std::string toStrMaxDecimals(double value, int decimals)
{
    std::ostringstream ss;
    ss << std::fixed << std::setprecision(decimals) << value;
    std::string s = ss.str();
    if(decimals > 0 && s[s.find_last_not_of('0')] == '.') {
        s.erase(s.size() - decimals + 1);
    }
    return s;
}

      



+9


a source


sprintf will be much simpler, more readable, and more performant than C ++ streams. You don't need to do the rounding or trimming yourself. Sprintf has flags for this. You probably want something like

sprintf(targetBuffer, "%.2g", floatingPointValue);

      

Sprintf does rounding in Java, and I'm pretty sure it will do in C ++ as well.

EDIT:



Sorry, the example code I wrote is for your example. For the original question, change% .2g to% .6g

EDIT:

Changed f to g to suppress trailing zeros.

+5


a source


Do you feel like using plain old sprintf for formatting?

It won't do what you want, but if you round to hundredths and then sprintf a number like% f (for float) or% lf (for double float).

To round to 100's, you could do num = num + ((int) (num - ((int) num)) * 100) / 100;

+1


a source







All Articles