0

Possible Duplicate:
Extract decimal part from a floating point number in C

I would like retrieve the decimal part of a double in the most efficient way.

Something like this:

double a = 1.5;
double decimal_part = a -1 ; // decimal_part = 0.5

How retrieve and store in a variable in a really efficient way the .5 (decimal part of a) ?

Community
  • 1
  • 1
pedr0
  • 2,941
  • 6
  • 32
  • 46

3 Answers3

5

Use modf function:

double integer_part;
double decimal_part = modf(a, &integer_part);
Vladimir
  • 170,431
  • 36
  • 387
  • 313
1

Use modf function from math.h for double and modff for float.

#include <math.h>

double val = 3.14159;
double integral_part;
double fractional_part;

/*
 * integral_part will be 3.0
 * fractional_part will be 0.14159
 */
fractional_part = modf(val, &integral_part);
ouah
  • 142,963
  • 15
  • 272
  • 331
0
double a = 5.6;
double f = a - int(a); // int(a) chops off fraction

you have to make sure ranges are sane st int doesn't overflow.

Anycorn
  • 50,217
  • 42
  • 167
  • 261