Home > Mobile >  how to take a double's fraction part and turn it into an integer? (c )
how to take a double's fraction part and turn it into an integer? (c )

Time:09-30

my goal is to turn a double's fraction part into an integer, for example: turn 0.854 into 854 or turn 0.9321 into 9321 (the whole part of the double is always 0)

i was doing it like this, but i dont know how to fill the while's parameters to make it stop when variable x becomes a whole number without a fraction:

double x;
cin >> x;
while(WHAT DO I TYPE HERE TO MAKE IT STOP WHEN X BECOMES A WHOLE NUMBER){
x *= 10;
}

it would be best if i could do it with a loop, but if it is not possible, i am open to other suggestions :)

CodePudding user response:

Using floor, you can check if the rounded down version of the number is the same as the variable. If so, it's a whole number:

int main() {
    double x;

    std::cin >> x;

    while (floor(x) != x) {
        x *= 10;
        std::cout << x << endl;
    }
}

CodePudding user response:

Compare the difference between double and integer part. It is working only if x is less than 2^63.

while (x - long long(x) > 0)

CodePudding user response:

if anyone comes around this post and has the same problem, doing it with a loop seems impossible, so i did it by making variable x a string, deleting the "0." and then converting it into int:

    #include <iostream>
    #include <sstream>
    
    using namespace std;
    
    int main(){
    string x;
    cin >> x;
    x.erase(0,2); //erase 2 first characters from the string
    int xConverted = stoi(x);
    cout << xConverted;
    return 0;
    }
  •  Tags:  
  • c
  • Related