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
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 to share