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,802
  • 5
  • 30
  • 44

3 Answers3

5

Use modf function:

double integer_part;
double decimal_part = modf(a, &integer_part);
Vladimir
  • 169,112
  • 36
  • 383
  • 312
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
  • 138,975
  • 15
  • 262
  • 325
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
  • 48,681
  • 42
  • 161
  • 257