Thread: Converting Strings To Doubles

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    139

    Converting Strings To Doubles

    Hello,

    I need to convert a string into a large number (I am using double because it has to have decimal places)

    Code:
    double ConvertStringToDouble(string s)
    {
        try
        {
            double d = 0.0d;
            d = stod(s);
            return d;
        }
        catch (exception ex)
        {
            return -1;
        }
    }
    Can someone please tell me why when I pass in
    string mystr = "2532068"

    it comes out as
    2.53207e+06

    Thanks in advance!

  2. #2
    Informer -Adrian's Avatar
    Join Date
    Jan 2013
    Posts
    779
    The conversion went fine, but you're seeing the result expressed in scientific notation. To change that behavior, you can pass a flag to the output stream, e.g.:

    Code:
    std::string num("2532068");
    double result = std::stod(num);
    
    std::cout << std::fixed << result << std::endl;
    Last edited by -Adrian; 05-11-2018 at 05:19 PM.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    26,944
    By the way, 0.0 is a double constant; there's no need to add a non-standard d suffix, although in that part you don't even need the variable named d because you could just return stod(s).

    Note that since you are returning -1 on conversion failure, you have no way to determine if a value of -1 is an error or a valid conversion, so this presupposes that in your context, -1 is never a valid value.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting Strings
    By EverydayDiesel in forum C++ Programming
    Replies: 2
    Last Post: 10-26-2015, 04:30 PM
  2. Converting Strings
    By EverydayDiesel in forum C++ Programming
    Replies: 6
    Last Post: 06-12-2014, 04:08 AM
  3. Converting strings
    By Scarvenger in forum Windows Programming
    Replies: 2
    Last Post: 11-13-2006, 04:36 PM
  4. Math Help! Converting Doubles
    By Conutmonky in forum C++ Programming
    Replies: 7
    Last Post: 07-06-2005, 01:26 PM
  5. converting c style strings to c++ strings
    By fbplayr78 in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 03:13 AM

Tags for this Thread