1

it is possible to do something like that

std::string str = "127,8";
double x = boost::lexical_cast<double>(str);

I tried it but it throws an exception, do u have a simple way to do such cast using boost ?

DoctorX
  • 73
  • 4
  • 1
    Does this answer your question? [Convert string to double variable which is seperated by a comma(0,07)](https://stackoverflow.com/questions/32013041/convert-string-to-double-variable-which-is-seperated-by-a-comma0-07) – NutCracker Mar 10 '22 at 12:22
  • For me it works for "127.8" and not for "127,8" but I know others use `,` instead of `.` for the decimal point: [http://cpp.sh/8dwdqe](http://cpp.sh/8dwdqe) – drescherjm Mar 10 '22 at 12:23

1 Answers1

2

You can use a custom locale that uses , for the decimal point. Code taken and modified from https://stackoverflow.com/a/7277333/4117728

#include <iostream>
#include <boost/lexical_cast.hpp>
class comma_numpunct : public std::numpunct<char>
{
  protected:
    virtual char do_decimal_point() const
    {
        return ',';
    }


};

int main(int argc, char *argv[]) {
    std::string str = "127,8";
    std::locale comma_locale(std::locale(), new comma_numpunct());
    std::locale::global(comma_locale);
    double x = boost::lexical_cast<double>(str);
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • you don't need a custom locale, most European locales use `,` for the radix point – phuclv Mar 10 '22 at 12:55
  • For OP: you can use `std::numpunct_byname("fr_FR.UTF8")` or any other locale having a comma as a decimal separator (Used OP's location, as defined in their profile). – YSC Mar 10 '22 at 13:27