omasoud
omasoud

Reputation: 479

Precision is lost when using lexical_cast<float>(string)

When using boost::lexical_cast (I'm using boost version 1.58 on VS2013), I can't get the exact value specified in the string, even though it is represent-able in float:

std::wstring t = L"91.25";
float r;
r = boost::lexical_cast<float>(t);

r is 91.249992 (0x42B67FFF) instead of 91.250000 (0x42b68000)

Prior versions of boost behaved the expected way. Is there a precision setting I'm missing?

Upvotes: 4

Views: 310

Answers (1)

omasoud
omasoud

Reputation: 479

It turns out this is unrelated to boost. It seems to be a problem with Visual Studio and only VS2013.

#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
    float a;
    std::stringstream s;
    s.str("91.25");
    s >> a;
    std::wcout << std::setprecision(20) << a << std::endl;
    // displays "91.249992370605469" when compiled with 
    // VS2013 and "91.25" when compiled with VS2010 or VS2015
    return 0;
}

Upvotes: 2

Related Questions