Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- double string_to_double(string * s) //convert string to double
- {
- int dot = -1;
- bool negative = false;
- int start = 0;
- if(s->at(0) == '-')
- {
- negative = true;
- start = 1;
- }
- for(int i = 0; i < s->size(); i++)
- {
- if(s->at(i) == '.')
- {
- dot = i;
- break;
- }
- }
- if(dot == -1)
- {
- double value = 0;
- for(int i = start ; i < s->size(); i++)
- {
- value *= 10;
- value += ((double)s->at(i) - 48); //must -48 since the typecast converts the string to ascii, not allowed to use std algos
- }
- if(negative)
- {
- return (value*-1);
- }
- return value;
- }
- else
- {
- double value = 0;
- for(int i = start; i < dot; i++)
- {
- value *= 10;
- value += ((double)s->at(i) - 48.0); // must -48 since the typecase converts the string to ascii, not allowed tto use std algos
- }
- double decimal_value = 0.0;
- for(int i = s->size()-1; i > dot; i--)
- {
- decimal_value /= 10;
- decimal_value += ((double)s->at(i) - 48); // must -48 since the typecast converts the string to ascii, not allowed to use std algos
- }
- decimal_value /= 10; //the last division is still at the ones place
- if(negative)
- {
- return ((value + decimal_value)*-1);
- }
- return value + decimal_value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement