djabhi121
djabhi121

Reputation: 27

extract value after decimal

I am taking a double number in a string because i want to extract its value after the decimal part I found concatenation not working properly here whats wrong with str2+=str[n-i] ?

    string str;
    cin>>str;
    int flag=0;
    string str2="";
    int n=str.length();
    for(int i=0;i<n;i++){
        if(str[n-i]=='.'){
            flag=1;
            break;
        }

        str2+=str[n-i];
        cout<<str2; 

    }
    reverse(str2.begin(),str2.end());
    int m = stoi(str2);

Upvotes: 1

Views: 474

Answers (2)

M.K
M.K

Reputation: 1495

I am not sure if I understood you properly, but here someone asked what you are asking.

I thought on doing this:

#include <iostream>

    using namespace std;

    int main()
    {
        double num1=2.323441;
        double num2=num1-(int)num1;
        cout<<num2;
        return 0;
    }

Printing result: 0.323441

But this does not give your expected result, that I think it is: 323441.

Then I guess there are 2 possible solutions:

The first, 'dirty' and easy one is that number you got, multiply it by 10*it's length: If there are 5 decimals, multiply it by 100000. This way, you'll get the 0.323441converted to 323441.

The Second, as the answer I linked says, use round and power of:

int fractional_part_as_int(double number, int number_of_decimal_places) {
    double dummy;
    double frac = modf(number,&dummy);
    return round(frac*pow(10,number_of_decimal_places));
}

Upvotes: 2

P.W
P.W

Reputation: 26800

  • Use std::stod to convert the string to double
  • Then use std::modf to decompose the floating point value into integral and fractional parts.

Or after having obtained the double value, you can just do:

double d = fpValue - (long)fpValue;

Upvotes: 1

Related Questions