0

I am trying to convert a string "500.00" into float.

When I use this it produces a string 50000, why does it produce such a result?

atof(bal.c_str());
3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by firstPerson
0

It works OK for me. Maybe the problem is how you are printing the double that atof() returns. What does the following program print when you run it?

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>

int main()
{
    std::string s("500.00");

    std::cout << std::fixed << std::setprecision(2)
              << std::atof(s.c_str()) << '\n';
}
0

ohh....I didnt include the setprecision and std::fixed. But if I include it, my code still doesnt print right. 500.00 as a string the float just becomes 50000.00

This is exactly what I did in my code.
It is in a function and I pass in string bal

float tt = atof(bal.c_str());
cout << tt;

Edited by number87: n/a

0

Use sstream;

#include<sstream>
#include<string>
using namespace std;
int main(){
   stringstream converter;
   string str= "3.14";
   converter << str ;  //put in string 
   float PI = 0;
   converter >> PI; //put out float
 return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.