944,221 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 562
  • C++ RSS
Oct 26th, 2009
0

string to float problem

Expand Post »
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?
C++ Syntax (Toggle Plain Text)
  1. atof(bal.c_str());
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
number87 is offline Offline
83 posts
since Jan 2008
Oct 26th, 2009
0
Re: string to float problem
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?
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cstdlib>
  5.  
  6. int main()
  7. {
  8. std::string s("500.00");
  9.  
  10. std::cout << std::fixed << std::setprecision(2)
  11. << std::atof(s.c_str()) << '\n';
  12. }
Reputation Points: 1446
Solved Threads: 135
Practically a Master Poster
Tom Gunn is offline Offline
681 posts
since Jun 2009
Oct 26th, 2009
0
Re: string to float problem
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

C++ Syntax (Toggle Plain Text)
  1. float tt = atof(bal.c_str());
  2. cout << tt;
Last edited by number87; Oct 26th, 2009 at 12:42 pm.
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
number87 is offline Offline
83 posts
since Jan 2008
Oct 26th, 2009
0
Re: string to float problem
Use sstream;
C++ Syntax (Toggle Plain Text)
  1. #include<sstream>
  2. #include<string>
  3. using namespace std;
  4. int main(){
  5. stringstream converter;
  6. string str= "3.14";
  7. converter << str ; //put in string
  8. float PI = 0;
  9. converter >> PI; //put out float
  10. return 0;
  11. }
Reputation Points: 840
Solved Threads: 594
Senior Poster
firstPerson is offline Offline
3,865 posts
since Dec 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: point me in the right direction please
Next Thread in C++ Forum Timeline: Extra Paramaters





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC