I am trying to convert a string to number(long double) in C++. The problem arises when the number of digits after decimal point is greater than 3. It automatically rounds-off the to the nearest third digit after the decimal.
Additional info:
- compiler: mingw
- os: win10
Here's the code (test.cpp):
#include<iostream>
#include <string>
#include <math.h>
using namespace std;
double long c2n(string n) {
    double long num=0;
    bool isdec = false, is_ve=false;
    // is_ve checks if number is negative
    // isdec checks if the decimal point is reached and numbers can be added after decimal
    char c;
    // to store the the character which needs to be checked
    short i = 0, count=1;
    if (n.at(0)=='-')
    {
        i=1;
        is_ve=true;
    }
    for (; i < n.length(); ++i)
    {
        c=n.at(i);
        if (c=='.'){
            isdec=true;
            continue;
        }
        if (!isdec)
            num=num*10+(c-'0');
        else{
            num = num + (c-'0')/pow(10,count);
            count++;
        }
    }
    if (is_ve)
    {
        return -num;
    }
    return num;
}
int main(int argc, char const *argv[])
{
    cout << c2n("-912.301956") << endl;
    return 0;
}
Here's the output:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302
What I discovered later:
if in the main function, we pass "-912.3016"
cout<< c2n("-912.3016") <<endl;
then output comes out to be:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.302
but if we pass "-912.3015"
cout << c2n("-912.3015") <<endl;
then the o/p:
D:\--path-->g++ -o test.exe test.cpp
D:\--path-->test.exe
-912.301
Should I take double instead of long double or there is any other problem?
 
    