Home > Net >  How to make a float number an integer in C?
How to make a float number an integer in C?

Time:11-12

I want to turn a number like 0.1235 to 1235.

i tried to do it through a loop by multiplying by 10 but i didnt know how to stop the loop.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main (){
    double a;

    printf("a:");
    scanf("%lf", &a);
    while (/* condition */)
    {
        a = a*10;
    }
    printf("a: %lf",a)
    getch ();
    return 0;

}

CodePudding user response:

int var = (int)round(0.1235 * 10000);

CodePudding user response:

This is not an easy problem to solve as it may seem at first due to decimal precision and lack of implementation details in your question. Here is an attempt of a solution to your problem, but you might need to adjust it depending on your needs.

#include <stdio.h>
#include <math.h>

#define DELTA 0.00001

int get_number_of_decimal_places(double num)
{
    int count = 0;
    
    do {
        num = num * 10;
          count;
    } while (num - (int)num > DELTA);
    
    return count;
}

int main()
{
    double a;
    int result = 0;

    printf("a:");
    scanf("%lf", &a);
    
    int decimal_places = get_number_of_decimal_places(a);
    
    do {
        a *= 10;
        result  = (int)a * pow(10, --decimal_places);
        a -= (int)a;
    } while (decimal_places != 0);
    
    printf("result: %d", result);
    getch();
    return 0;
}

For input value 0.12345, the output is:

12345

Keep in mind that this solution treats input values 0.1, 0.0001, 0.010 etc. the same way, so the output would be:

1
  • Related