Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the decimal part from a floating point number in C?

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?

like image 785
Binu Avatar asked Feb 01 '09 00:02

Binu


People also ask

How do you get the decimal part of a float?

Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you extract the decimal part of a number?

The TRUNC function simply truncates (i.e. removes) decimal values if they exist – it doesn't do any rounding. The TRUNC function returns the integer portion of the number which is then subtracted from the original value. The result is the decimal portion of the number.

How do you find a fractional part of a number in C?

In the C Programming Language, the modf function splits a floating-point value into an integer and a fractional part. The fraction is returned by the modf function and the integer part is stored in the iptr variable.

Can float take decimal values?

The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.


2 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.

like image 133
Johannes Schaub - litb Avatar answered Oct 13 '22 06:10

Johannes Schaub - litb


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.

like image 34
Chris Bunch Avatar answered Oct 13 '22 05:10

Chris Bunch