MistyD
MistyD

Reputation: 17253

String to float conversion and formatting

Currently I have something like this

float a = SomeQString.toFloat(); //QString has 2.37

Now float is 2.3690000031..

What I want is 2.3700000000.. any suggestion on how i could do that ? Also why am i getting 2.369 instead of 2.37?

Upvotes: 2

Views: 5178

Answers (3)

László Papp
László Papp

Reputation: 53235

If you insist on using Qt, this is the appropriate code for you:

#include <QString>
#include <QTextStream>
#include <QDebug>

using namespace std;

int main()
{
    QString floatString = "2.37";
    QTextStream floatTextStream(&floatString);
    float f;
    floatTextStream >> f;
    qDebug() << f;

    return 0;
} 

Run the following command with gcc for instance, and Qt 5 (or something similar if you have a different scenario):

Command: g++ -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core -fPIC main.cpp && ./a.out

Output: 2.37

However, You do not need QString for doing this. See the code below which generates the output 2.37 as expected.

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    string floatString = "2.37";
    istringstream floatStringStream(floatString);
    float f;
    floatStringStream >> f;
    cout << f;

    return 0;
}

Run the following command with gcc for instance (or something similar if you have a different scenario):

Command: g++ main.cpp && ./a.out

Output: 2.37

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320797

(Has been asked and explained so many times.) It is not possible to get 2.37 in a float. It is not possible to get 2.37 in a double. It is not possible to get 2.37 in any IEEE-754 style binary floating-point format. 2.37 is not representable precisely in such binary floating-point formats.

Read What Every Computer Scientist Should Know About Floating-Point Arithmetic

One viable way to "obtain" 2.37 is actually to store that 2.369... in a float (which is what you do already) and then round it to 2.37 at the time when you'll need to generate the decimal representation, i.e. at the time when you have to present/output the value to the user.

Upvotes: 5

Abhineet
Abhineet

Reputation: 5409

#include <string>
#include <sstream>

int main(void)
{
    std::string QString = "2.37";
    std::istringstream StrToFloat(QString );
    float floatVar;
    StrToFloat >> floatVar;

    return 0;
}

Upvotes: 2

Related Questions