How to convert std::string_view to double?

Since you marked your question with C++1z, then that (theoretically) means you have access to from_chars. It can handle your string-to-number conversion without needing anything more than a pair of const char*s:

double dbl;
auto result = from_chars(value_str.data(), value_str.data() + value_str.size(), dbl);

Of course, this requires that your standard library provide an implementation of from_chars.


Headers:

#include <boost/convert.hpp>
#include <boost/convert/strtol.hpp>

Then:

std::string x { "aa123.4"};
const std::string_view y(x.c_str()+2, 5); // Window that views the characters "123.4".

auto value = boost::convert<double>(y, boost::cnv::strtol());
if (value.has_value())
{
    cout << value.get() << "\n"; // Prints: 123.4
}

Tested Compilers:

  • MSVC 2017

p.s. Can easily install Boost using vcpkg (defaults to 32-bit, second command is for 64-bit):

vcpkg install boost-convert
vcpkg install boost-convert:x64-windows

Update: Apparently, many Boost functions use string streams internally, which has a lock on the global OS locale. So they have terrible multi-threaded performance**.

I would now recommend something like stoi() with substr instead. See: Safely convert std::string_view to int (like stoi or atoi)

** This strange quirk of Boost renders most of Boost string processing absolutely useless in a multi-threaded environment, which is strange paradox indeed. This is the voice of hard won experience talking - measure it for yourself if you have any doubts. A 48-core machine runs no faster with many Boost calls compared to a 2-core machine. So now I avoid certain parts of Boost like the proverbial plague, as anything can have a dependency on that damn global OS locale lock.