I wrote a program to read lines from file, which has few float numbers written on it, length of decimals is 6 to 7 , but when converted to float using stof() length of decimal reduces to 4, I cross checked with string parameter of stof() ,it was correct , output written at end of code,
my question is how to make stof return full decimal value to string
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::string line = "20.2783121";
float lat = std::stof(line);
std::cout << std::fixed << std::setprecision(7);
std::cout << "lat: " << lat << '\n';
std::cout << "line: " << line << '\n';
}
lat: 20.2783127
line: 20.2783121
The reason the last digit is not outputted correctly is because float doesn't have enough precision. Use double and std::stod if you want better precision.
First why are you using getline() instead of directly reading the floating point numbers?
Second there is no problem with the stof(), the problem is with how you are attempting to print the number. You need to tell the operator<< that you want to print more decimals by using std::setprecision().
I can understand your point for more complicated code but for basic code there is nothing wrong with skipping the string and going straight into a numeric variable. Also just using getline() is not the whole ball of wax, you still need to handle data errors.