Search code examples
cintegerdigits

Separating digits from a float


I need a simple function that has 3 variables: l (left), m (middle), and r (right) So

int l,m,r

And when I put in the number 27.2 l should become 2 m should become 7 r should become 2 I can think of dividing the left 2 by deviding by 10 and then cast to int but the other 2 numbers?


Solution

  • Let your number be stored in x.

    float x = 36.2;
    x = x*10;
    int r = (int)x%10;
    x = x/10;
    int m = (int)x%10;
    x = x/10;
    int l = (int)x%10;
    printf("%d, %d, %d",l, m, r);