How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?
If you just want to get the first decimal value, the solution is really simple.
Here's an explanatory example:
int leftSideOfDecimalPoint = (int) initialFloatValue; // The cast from float to int keeps only the integer part
int temp = (int) initialFloatValue * 10;
int rightSideOfDecimalPoint = temp % 10;
Say for example we have an initial float value of 27.8 .
This technique can then be used to get the following decimal characters by using for example 100 instead of 10, and so on.
Just take note that if you use this technique on real-time systems, for example to display it on a 7-segment display, it may not work properly because we are multiplying with a float value, where multiplication takes a lot of overhead time.
cout<<"enter a decimal number\n";
cin>>str;
for(i=0;i<str.size();i++)
{
if(str[i]=='.')
break;
}
for(j=i+1;j<str.size();j++)
{
cout<<str[j];
}
I made this function, it seems to work fine:
#include <math.h>
void GetFloattoInt (double fnum, long precision, long *pe, long *pd)
{
long pe_sign;
long intpart;
float decpart;
if(fnum>=0)
{
pe_sign=1;
}
else
{
pe_sign=-1;
}
intpart=(long)fnum;
decpart=fnum-intpart;
*pe=intpart;
*pd=(((long)(decpart*pe_sign*pow(10,precision)))%(long)pow(10,precision));
}
#include <stdio.h>
Int main ()
{
float f=56.75;
int a=(int)f;
int result=(f-a)*100;
printf ("integer = %d\n decimal part to integer
=%d\n",result);
}
Output:-
integer =56
decimal part to integer = 75
The quick "in a nut shell" most obvious answer seems like:
#define N_DECIMAL_POINTS_PRECISION (1000) // n = 3. Three decimal points.
float f = 123.456;
int integerPart = (int)f;
int decimalPart = ((int)(f*N_DECIMAL_POINTS_PRECISION)%N_DECIMAL_POINTS_PRECISION);
You would change how many decimal points you want by changing the N_DECIMAL_POINTS_PRECISION
to suit your needs.
I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part. But, it won't work for all cases (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char s_value[60], s_integral[60], s_fractional[60];
int i, found = 0, count = 1, integral, fractional;
scanf("%s", s_value);
for (i = 0; s_value[i] != '\0'; i++)
{
if (!found)
{
if (s_value[i] == '.')
{
found = 1;
s_integral[i] = '\0';
continue;
}
s_integral[i] = s_value[i];
count++;
}
else
s_fractional[i - count] = s_value[i];
}
s_fractional[i - count] = '\0';
integral = atoi(s_integral);
fractional = atoi(s_fractional);
printf("value = %s, integral = %d, fractional = %d\n",
s_value, integral, fractional);
return 0;
}