简体   繁体   中英

Is there a way to convert a string into a float without losing accuracy?

I have float values with high precision. When I convert them to a string I lose precision.

I am storing this float value in a Json::Value object. And I need to later take the float back out of the Json::Value object without losing precision.

I am using this float value to predict values. When the float loses precision the prediction is weaker. Before I put it into this Json object it is making more accurate calculations.

Here is the code:

#include <sstream>
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

using namespace std;

int main(int argc, char **argv)
{
    float num = 0.0874833928293906f;
    
    Json::Value weight(num);
    
    cout << "Original float value: " << num << endl;
    cout << "Original float value being stored in Json::Value: " << weight.asString() << endl;

    num = weight.asFloat();

    cout << "Float once being converted back to float from string: " << num << endl; 
}

Output:

Original float value: 0.0874834
Original float value being stored in Json::Value: 0.087483391165733337
Float once being converted back to float from string: 0.0874834

As you can see the float value retains its precision upon input to json and is being stored as a json double. When I convert the float to a string it loses precision. When I convert the Json::Value object to a float it loses precision.

Because the output of the calculation changed I know that the float is being represented differently before and after.

Is there any way I can keep the precision that the float had before after holding it in a Json::Value object?

how about use int instead of float during transport (like multiply by 10000000000), and convert back to float in you business code.

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