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?


Recommended Answers

All 3 Replies

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';

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;

Use sstream;

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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.