Hi, I'm trying to convert a string to a double. The string should be in this format: "0.04". However, when I convert from a string to a double using atof, the new double's value is "0.0400000000001". How do I get it to just convert two the two decimal place without adding all of the extra numbers at the end?
I might be mistaken here, but I believe you're getting that one all the way at the end bc of the string being terminated. I personally don't know of a way to predict the end of the string. But have you tried casting the string to a float? I personally only use strings for letters and words. If a number is put in, I use number data types. Maybe look up what the terminating character is first, remove it from the end of the string and convert?
The program that I'm writing reads from a csv file using fstream and getline. I've created an algorithm that extracts the prices from the getline string into another string using substr.
int main()
{
vector<test> test(100); // Vector of objects
int noOfTest = 0; // Number of vector objects (a counter of objects)
importPrices(test, noOfTest); // Calls the member function importPrices
return 0;
}
void importPrices(vector<test>& test, int& noOfTest)
{
ifstream fin("test.csv"); // The csv file to read
string input; // String the store the line
while(getline(fin, input))
{
test[noOfTest].setPrice(getPrice(input)); // Calls the function getPrice to return a string in a double format for the object
++noOfTest; // Increments the counter for the objects
}
}
double getPrice(string input)
{
.... // Algorithm to pull the price from the string
string test = "0.04" // Algorithm finds the price
double price = atof(test.c_str());
return price;
}
I'm not sure if I can cast the string as a float in my case. Hopes this puts it into a better perspective.