0

I've got a small C++ problem. First of all, "my" language is Java, so I'm new to C++. I have this function:

double readableDouble( double input )
{
    return   (int)(input*100+0.5)/100.0;
}

As you can see, nothing special. Now I call the function from another function (in the same class):

        cout << readableDouble(4434.21121131234323243) <<endl; // result: 4434.22 all okay
        cout << readableDouble(tempTrack.getLenght()/1000.0); // result: 30.56 all okay
        string lenght = boost::lexical_cast<string>(readableDouble((tempTrack.getLenght()/1000.0))); // result 30.55999999999982. expected: 30.56

getLenght() returns a double. (same double for both calls)

I am not quite sure how this is happening?

.

Mirco
  • 2,940
  • 5
  • 34
  • 57

1 Answers1

3

From another post (Credit to Mic):

From the documentation for boost lexical_cast:

For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional stringstream approach is recommended. Where the conversions are numeric to numeric, numeric_cast may offer more reasonable behavior than lexical_cast.

Example:

#include <sstream>

    #include <iomanip>

    int main() {
        std::ostringstream ss;
        double x = 5;
        ss << std::fixed << std::setprecision(2);
        ss << x;
        std::string s = ss.str();
        return 0;
    }
Community
  • 1
  • 1
David D
  • 1,571
  • 11
  • 12