How do I write a function that formats a string with decimals digits, without trailing 0's or unnecessary 9's? Given that decimals is 2, here's 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'd expect)
Here's what I have so far, but it's pretty ugly code. Is there a nicer 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;
}