How to convert string format number (22.123) to float variable format without using any API in C ++

How to convert string format number (22.123) to float variable format without using any API in C ++. This is just to better understand internal coding .. thnx

+3
source share
5 answers

sort of:

double string_to_double(std::string s)
{
    int p = 0;
    int p_dec = s.length();

    double val = 0;

    for (int i=0; i<s.length(); ++i)
    {
        double digit = (double)(s[i] - '0');
        if (s[i] == '.') { p_dec = p; }
        else { val += digit*powf(10,p--); }
    }

    val /= powf(10, p_dec);
}
+3
source

The main algorithm that does not accept input in the form 1.2e-4:

(1) Read the integer before the dot. If the number of digits is> 16 (normal precision double), convert that integer to a floating point directly and return.

(2) 16 . ( ) ; 10 . (1) .

2 : + & divide;, . 10 , .

( 16- , 64- int.)


sscanf(str, "%lf", ...), std::istringstream boost::lexical_cast<double>.

+2

, 10 .

0

Source: https://habr.com/ru/post/1736264/


All Articles