Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing float function in C++

My question is regarding the solution posted by 6502 on [c++ stringstream is too slow, how to speed up? Parsing Float method posted by him is fast but its not giving correct result on large double values.

Input:

132.12345645645645

Output:

132.123

double parseFloat(const std::string& input){
    const char *p = input.c_str();
    if (!*p || *p == '?')
        return NAN_D;
    int s = 1;
    while (*p == ' ') p++;

    if (*p == '-') {
        s = -1; p++;
    }

    double acc = 0;
    while (*p >= '0' && *p <= '9')
        acc = acc * 10 + *p++ - '0';

    if (*p == '.') {
        double k = 0.1;
        p++;
        while (*p >= '0' && *p <= '9') {
            acc += (*p++ - '0') * k;
            k *= 0.1;
        }
    }
    if (*p) die("Invalid numeric format");
    return s * acc;
}

I want to know is there any way to change this function to get correct result.

like image 608
sv_jan5 Avatar asked May 16 '26 13:05

sv_jan5


1 Answers

If you're printing the result with cout, make sure you set the necessary precision:

cout.precision(20);

live example

However as you noted a simpler method would be:

double string_to_double( const std::string& s )
 {
   std::istringstream i(s);
   double x;
   if (!(i >> x))
     return std::numeric_limits<double>::quiet_NaN(); // Or anything you prefer
   return x;
 }

Notice: due to roundoff errors, exceeding with the number of digits might not yield 100% expected results on the rightmost part.

like image 178
Marco A. Avatar answered May 18 '26 03:05

Marco A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!