Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. double string_to_double(string * s) //convert string to double
  2. {
  3.     int dot = -1;
  4.     bool negative = false;
  5.     int start = 0;
  6.     if(s->at(0) == '-')
  7.     {
  8.         negative = true;
  9.         start = 1;
  10.     }
  11.     for(int i = 0; i < s->size(); i++)
  12.     {
  13.         if(s->at(i) == '.')
  14.         {
  15.             dot = i;
  16.             break;
  17.         }
  18.     }
  19.     if(dot == -1)
  20.     {
  21.         double value = 0;
  22.         for(int i = start ; i < s->size(); i++)
  23.         {
  24.                 value *= 10;
  25.                 value += ((double)s->at(i) - 48); //must -48 since the typecast converts the string to ascii, not allowed to use std algos
  26.         }
  27.         if(negative)
  28.         {
  29.             return (value*-1);
  30.         }
  31.         return value;
  32.     }
  33.     else
  34.     {
  35.         double value = 0;
  36.         for(int i = start; i < dot; i++)
  37.         {
  38.             value *= 10;
  39.             value += ((double)s->at(i) - 48.0); // must -48 since the typecase converts the string to ascii, not allowed tto use std algos
  40.         }
  41.         double decimal_value = 0.0;
  42.         for(int i = s->size()-1; i > dot; i--)
  43.         {
  44.             decimal_value /= 10;
  45.             decimal_value += ((double)s->at(i) - 48); // must -48 since the typecast converts the string to ascii, not allowed to use std algos
  46.         }
  47.         decimal_value /= 10; //the last division is still at the ones place
  48.         if(negative)
  49.         {
  50.             return ((value + decimal_value)*-1);
  51.         }
  52.         return value + decimal_value;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement