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?
-
1I don't see how you could put the decimal part into an integer unless you knew how many digits you wanted to keep. Could you give a few examples?– NosrednaFeb 1, 2009 at 1:16
-
i want to get the decimal part as integer for any inputting value. so the number of digits in the deciaml part cannot predict.– BinuFeb 1, 2009 at 1:25
-
like if u input 16.25 i want to get 25 in an integer value also if teh nuber is 0.3215769 i want to get 3215769 in an integer like that– BinuFeb 1, 2009 at 1:33
-
reading into a string, then checking to see whether the string is a double (questions exist on SO that are answered saying how to do that), and then getting the stuff after the ".". what about that? or do you need to read other formats too (10e-5)?– Johannes Schaub - litbFeb 1, 2009 at 1:49
-
9How would you distinguish the decimal fractions in 1.5 and 1.005?– SingleNegationEliminationJun 5, 2009 at 12:16
16 Answers
You use the modf function:
double integral;
double fractional = modf(some_double, &integral);
You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.
-
2@penu It's because you are using
%dfor printingdouble. Here is the working code: codepad.org/kPGKtcZi Mar 20, 2016 at 19:47 -
1This code truncates 123.456745693850 from 0.45674569385 to 0.456746– user5125586Feb 24, 2021 at 9:13
-
@Richard you can open a new stackoverflow question to ask why it would do that on your machine. I have no idea. Feb 25, 2021 at 21:30
-
On my machine, man pages for modf gives me the signature
double modf(double x, double *iptr);, but I have some compiler implementation headers which uses float instead of double. Maybe this is why truncation to float may happen... I think I'll prefer the int cast + subtraction solution to avoid this issue... Jan 12 at 3:05
Try this:
int main() {
double num = 23.345;
int intpart = (int)num;
double decpart = num - intpart;
printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}
For me, it produces:
Num = 23.345000, intpart = 23, decpart = 0.345000
Which appears to be what you're asking for.
-
1the first part is correct but wish to get the result as decimal part as 345000 integer– BinuFeb 1, 2009 at 1:03
-
1but i want to get the deciaml part as Integer value which means decpart=345000– BinuMar 14, 2009 at 16:11
-
3
-
2This method is susceptible to some nasty floating-point problems. Try setting
num = 1.1for a quick example. As a floating-point numberdecpartcannot represent0.1.– 0b101010Apr 28, 2015 at 15:50 -
Regarding the second line of the method: did C require a cast back in '09? Or is it just there for clarification? Oct 26, 2022 at 12:13
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.
-
1Just for fun. Let's do a thought experiement: The more obfuscated and complex ( see "hard to maintain code" ) solution could go as far as [bit slicing][1] the float or double to get the actual ["integerBits" and "fractionalBits"][2]. Mar 26, 2009 at 3:53
-
I'm not exactly sure of why you would do this... maybe this method would have the advantage of capturing the integer and decimal parts directly without losing any of the precision due to floating point rounding. Mar 26, 2009 at 3:54
-
Here is some incomplete pseudo code to give you the idea: #define BIT_MASK1 /* not sure / #define SHIFT / not sure / #define BIT_MASK2 / not sure */ float f = 123.456; uint32_t * tmp = (uint32_t *)&f; int integerPart = (int)f; Mar 26, 2009 at 3:55
-
int decimalPart = (((*tmp)&BIT_MASK1)>>SHIFT)&BIT_MASK2; [1]: en.wikipedia.org/wiki/Bit_mask [2]: en.wikipedia.org/wiki/Q_(number_format) Mar 26, 2009 at 3:56
I created a subroutine one using a double float, it returns 2 integer values.
void double2Ints(double f, int p, int *i, int *d)
{
// f = float, p=decimal precision, i=integer, d=decimal
int li;
int prec=1;
for(int x=p;x>0;x--)
{
prec*=10;
}; // same as power(10,p)
li = (int) f; // get integer part
*d = (int) ((f-li)*prec); // get decimal part
*i = li;
}
void test()
{
double df = 3.14159265;
int i,d;
for(int p=2;p<9;p++)
{
double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
}
}
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;
}
-
3You solved the problem in a way nobody should ever attempt to solve it. Jan 24, 2020 at 1:04
Use the floating number to subtract the floored value to get its fractional part:
double fractional = some_double - floor(some_double);
This prevents the typecasting to an integer, which may cause overflow if the floating number is very large that an integer value could not even contain it.
Also for negative values, this code gives you the positive fractional part of the floating number since floor() computes the largest integer value not greater than the input value.
-
Try it with a number such as 10.2346789358 and you will get 0.2346789357999999 in return which is wrong.– user5125586Feb 24, 2021 at 9:10
-
2In the context of
double, 0.2346789357999999 is one of several correct answers, depending on exactly how the value is encoded, compiler flags, architecture, processor flags, etc. Floating point types are not decimal.– buritoOct 14, 2021 at 19:04
Here is another way:
#include <stdlib.h>
int main()
{
char* inStr = "123.4567"; //the number we want to convert
char* endptr; //unused char ptr for strtod
char* loc = strchr(inStr, '.');
long mantissa = strtod(loc+1, endptr);
long whole = strtod(inStr, endptr);
printf("whole: %d \n", whole); //whole number portion
printf("mantissa: %d", mantissa); //decimal portion
}
Output:
whole: 123
mantissa: 4567
-
1Your code won’t work on 16 bits platforms where longs are 32 bits and long double are 53 bits. May 3, 2015 at 15:37
float num;
int intgPart;
float fracPart;
printf("Enter the positive floating point number: ");
scanf("%f", &num);
intgPart = (int)num;
fracPart = num - intgPart;
The fractional part can be obtained by subtracting an integral part from the original double value.
Maybe the best idea is to solve the problem while the data is in String format. If you have the data as String, you may parse it according to the decimal point. You extract the integral and decimal part as Substrings and then convert these substrings to actual integers.
-
Converting it to a string just for this is a bit silly, but if it were a string originally then this makes sense. Apr 24, 2012 at 21:12
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));
}
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 .
- By just casting the initial float value to an int, you discard the fraction part and only keep the integer part.
- By multiplying the initial float value by 10 we get a result of 278.0, then by casting this result to int, gives you the value of 278
- If we divide 278 by 10, we get 27.8, of which the remainder is 8, which is the value at the right side of the decimal point. Thus use modulus.
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.
#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
-
You assume here that decimal part is only two digits wide. That may not be case. Mar 19, 2018 at 12:38
-
1Although your code snippet might solve the issue, you should describe what’s the purpose of your code (how it solves the problem). Furthermore, you might want to check stackoverflow.com/help/how-to-answer– Ahmad FMar 19, 2018 at 14:29
Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.
My printf() didn't support formatting for floats. This was my solution to print it as two integers. Change 100 in to what you like to increase the precision.
I found this one
#define DEC(f) (uint32_t)(100*((f)-(float)((uint32_t)(f))))
#define INT(f) (uint32_t)(f)
DEC(3.1416..) = 14 (int)
INT(3.1416..) = 3 (int)
Let me know what you think of this solution.
Even I was thinking how to do it. But I found a way. Try this code
printf("Enter a floating number");
scanf("%d%c%d", &no, &dot, &dec);
printf("Number=%d Decimal part=%d", no, dec);
Output:-
Enter a floating number
23.13
Number=23 Decimal part=13
-
1
-
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];
}
-
1
-
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Feb 14, 2017 at 14:59
-
This answer is not helpful to the questioner. The code is entirely wrong! Why are you using Strings?– tripulseJun 5, 2019 at 14:44