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

Time:09-05

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?

CodePudding user response:

updated answer:

as @njuffa mentioned, your demo code maybe issue of textual representation, i write code to test it as below

    float num = 0.0874833928293906f;//maybe this is the precision lost place, it's not about jsoncpp
    
    Json::Value weight(num);
    float back_num = weight.asFloat();

    if (memcmp(&num, &back_num, sizeof(num)) == 0)
    {
        std::cout << "num and back_num is identical" << std::endl;
    }
    else
    {
        std::cout << "num and back_num is not identical" << std::endl;
    }

and the output is:

num and back_num is identical

I even tried json serilize and deserilize, the result is still identical.

So I think maybe the precision lost problem is not caused by jsoncpp, you should dig a little more to find the real issue.

original answer:

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

  • Related