Home > Enterprise >  Rounding converting from string to double/float
Rounding converting from string to double/float

Time:11-02

I am trying to extract a number from a string and convert it into a double or float so I can do some numerical operations on it. I am able to isolate the variable I need so the string consists only of the number, but when I try to convert it to a float or double it rounds the value, ie from 160430.6 to 160431.

//Helper Function to Extract Value of Interest
//Based on column of final digit of numbers being same across various FLOPS output files
double findValue(string &line, int &refN){
    setprecision(100);
    string output;
    
    //go to end column and work backwards to get value string
    while(line[refN] != ' '){
        output = line[refN]   output;
        refN = refN - 1;    

    }
    
    const char* outputx = output.c_str();
    double out = atof(outputx);
    //removing the const char* line and replacing atof with stod(output) runs into the same issue
    
    return out;
}

int main()
{
    string name;
    cin >> name;
    ifstream file(name);
    //opens file
    if(!file.is_open()){"error while opening the file";
    
    }else{
        //Temporary Reference Definitions
        string ref = "TOGW";
        int refN = 25;
        string line = findLine(file,ref);
        
        double MTOGW = findValue(line, refN);
        cout << MTOGW;
    }
    return 0;
}

I initially tried using stof() to convert, but that rounded. I have also tried using stod() and stold(), and last tried converting to a const char* and using atof(). I have messed with the setprecision() value, but also have not been able to solve it that way.

I cannot use Boost

CodePudding user response:

You were almost there. The rounding was occurring on output, so that's where you need to use setprecision. That and always use double instead of float to ensure you have enough precision in your variables.

#include <vector>
#include <ranges>
#include <iomanip>
#include <iostream>
#include <string>

using std::string;

double findValue(string &line, int &refN){
    //setprecision(100);
    string output;
    
    //go to end column and work backwards to get value string
    while(line[refN] != ' '){
        output = line[refN]   output;
        refN = refN - 1;    

    }
    
    const char* outputx = output.c_str();
    double out = strtod(outputx, NULL);
    
    return out;
}

int main()
{
    string s = " 160430.6";
    int n = s.size() - 1;
    std::cout << std::setprecision(10) << findValue(s, n) << '\n';
}

See it in action on the Godbolt compiler.

  •  Tags:  
  • c
  • Related