user3198149
user3198149

Reputation: 3

convert float pointing number to integer in c programing

I have a sine equation which return a float value like:

0.0034,.000006,6.1684332059801899768737349875082e-4.

I want to convert the corresponding float value to integer variables and pass it to a register to generate the particular sine wave graph.

Please help me out.

Upvotes: 0

Views: 155

Answers (2)

Eduard G
Eduard G

Reputation: 515

You could try to save the float value into 3 unsigned integers, one for the values left of the decimal point and two for the values on the right of the decimal point. For example, we get the float number "359.042042" and save it as variable flt.

int main(void)
{
    unsigned int int1, int2, int0;

    float flt = 359.042042;

    int1 = floor(flt);
    int2 = (flt - int1) * pow(10.0, 8.0);
    int0 = 8 - log10(int2);

    printf("%d.", int1);
    while (int0 != 0)
    {
        printf("0");
        int0--;
    }
    printf("%d", int2);

    return 0;
}

int1 are the digits on the left side of the decimal points, int2 are the digits on the right and int0 are the "0" before int2. This would print "359.042042". Good luck.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881473

If you're getting values like 0.0034, you can't simply cast that to an int since it will come out as zero. In fact, the majority of floating point values between zero and one will come out as zero.

You need to first scale up the value, then cast it to an integer.

For example, to turn the output of a sine function into a value between -100 and 100, you could use something like:

int val = (int)(fpVal * 100);

That will turn the range (-1,1) (but mostly 0) into something more usable, (-100,100) (with slightly better distribution across the range).

You may also want to round the value rather than truncate it, to ensure the values generated more accurate represent the inputs.

Upvotes: 4

Related Questions