0

I refered below question but I need to extract the digits after decimal and store in char *array

1.How to store float in array of float[]

2.Extract digits in float in python

Ex:

 float = 1.24456

My length of char *array is 2

Expected Output:

array[0] = 2;
array[1] = 4;
array[2] = 4;

I need to implement this in C dynamically.

Jennifer
  • 119
  • 1
  • 8

4 Answers4

4

You can isolate the fractional part of a float by using the function modff in <math.h>, which returns the fractional part as the function's return value and the whole-number part as an argument by reference:

float f = 3.141592f;
float numpart, fracpart;
fracpart = modff(f, &numpart);

Once you're done that, you can create a string with a conventional string-building function:

char buf[100];
snprintf(buf, 100, "%f", fracpart);

Another option is converting the entire float to a string, and then using strchr(float_str, '.') to isolate the decimal part:

char floatbuf[100], decibuf[100], *p;
float f = 3.141592f;

snprintf(floatbuf, 100, "%f", f);
if ((p = strchr(floatbuf, '.')) != NULL)
{
    strcpy(decibuf, p + 1);
    puts(decibuf);
}
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
0

Slightly more mathematical approach, but arguably less flexible would be this:

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

int main()
{
    float num = 1.24456;
    int num_noDecimals = (int)num; //truncate decimals in original number
    float num_onlyDecimals = num - (float)num_noDecimals; //obtain only the number after decimal
    int x = 4; //number of digits past decimal to extract
    num_onlyDecimals = num_onlyDecimals*pow(10,x); //move extracting digits left of decimal
    int digits_forArray = (int)num_onlyDecimals; //truncate remaining digits right of decimal
    char arr[x];
    for(int i=x-1; i > -1; i--) { arr[i] = (char)(digits_forArray%10); digits_forArray = digits_forArray/10; }
    for(int i=0;i<x;i++) { printf("arr[%d] = %d\n",i,arr[i]); }
}

Hopefully it's commented well enough to understand the steps being taken here.

0

In my code, I removed the integer part, then I reverse the float part to integer part by multiply each number of the float part by the number 10 then I classify each digit of in the array

My code :

int main()
{
    float n = 1.2445601;
    int m=(int)n;
    float p=n-m;
    int x=7,i=0,tab[x];
    while(i<x)
    {
        p=p*10;
        i++;
    }
    i=6;
    while((int)p!=0)
    {
        tab[i--]=(int)p%10;
        p=p/10;
    }

    for(int k=0;k<x;k++)
    {
         printf("\narray[%d] = %d ;",k,tab[k]);
    }
    printf("\n");
    return 0;
}
MED LDN
  • 684
  • 1
  • 5
  • 10
-2

If you just want the digits after the decimal point in variable, you could just have number - floor(number)

for example, if your number was 3.25, the calculation would be 3.25 - 3. This will give 0.25

Helper
  • 1
  • 1
  • 1
    This answer is just plain wrong, and has nothing to do with the question. I would recommend removing it. – GuedesBF Jun 29 '21 at 11:18