简体   繁体   中英

double to string conversion with fixed precision and no trailing zeros

I have to convert a double value to string , by using a specified number of digits after the dot. However I have to avoid printing trailing zeros, so if doubleValue is 95 , I want to see "95" and not "95.000000..." , and similarly, if the value is 95.5 , I want to see "95.5" and not "95.500000..." .

This is my current code, using boost::format :

double doubleValue = ...;
std::string fmt = (boost::format("%%.%df") % opts.floatPrecision).str();
return (boost::format(fmt) % doubleValue).str();

However it does not handle the two special cases I mentioned (not printing trailing zeros, and no dot in case of int).

I guess I can remove all trailing zeros from the string, and finally remove the trailing dot if any.

But I'm asking if there is a smarter way to do it.

This is what I've done:

std::string fmt = (boost::format("%%.%df") % opts.floatPrecision).str();
std::string s = (boost::format(fmt) % doubleValue).str();
int len = s.length();
while(s[len - 1] == '0') len--;
if(s[len - 1] == '.') len--;
return s.substr(0, len);

Note: it is not mandatory to use boost, but since I use it already in my project, it comes in handy.

Given all the issues in attempting to use a decimal format to represent a binary floating point type, if I were you, I'd adopt the following scheme:

  1. Use your favourite formatter to produce a string representation of your double , rounded to DBL_DIG - 1 significant figures (let the formatter do that, rather than rounding the double numerically).

  2. Trim any excess 0 after the decimal separator yourself.

You might find this hard to believe, but your requirement is rather idiosyncratic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM