
I'm using boost::lexical_cast to convert strings to double. However I just run into a string with a percent sign where boost::lexical_cast throws boost::bad_lexical_cast. As far as I can see there is no way to configure boost::lexical_cast to convert eg. "60%" to 0.6. I also checked out boost::numeric_cast but from what I read I think it doesn't help either. Is there anything in Boost which I can use to convert a more descriptive string like "60%" to a double? Boris

Is there anything in Boost which I can use to convert a more descriptive string like "60%" to a double?
The real answer is I don't know but maybe something like the following should do: double str_to_double(const std::string& s) { assert(!s.empty()); if(str[str.size() - 1] == '%') return str_to_double(s.substr(0, s.size() - 2)); return boost::lexical_cast<double>(s) / 100.0; }

Philippe Vaucher wrote:
Is there anything in Boost which I can use to convert a more descriptive string like "60%" to a double?
The real answer is I don't know but maybe something like the following should do:
Yes, I use now "something like this". :) However I wonder if there is something more comfortable. The facets in std::locale::numeric seem to support all kinds of punctuation but no percent sign. Boris

On Thu, 29 Jun 2006 18:58:26 +0200, "Boris" <boriss@web.de> wrote:
Yes, I use now "something like this". :) However I wonder if there is something more comfortable.
Yes, writing a small percentage class ;) boost::lexical_cast is about textual conversions, as performed by a standard stream with no special formatting (with a special treatment, explained in the docs, for string targets). "60%" is not a textual representation of a double in the standard lib view of things, thus you have no luck with that; but you can decide how *your classes* are streamed. Requirements indicated here <http://www.boost.org/libs/conversion/lexical_cast.htm#lexical_cast> are to be fulfilled for the class to work with lexical_cast<>. -- [ Gennaro Prota, C++ developer for hire ] [ resume: available on request ]
participants (3)
-
Boris
-
Gennaro Prota
-
Philippe Vaucher