0

The issue that i encounter is when i try to separate the integer and fractional part of a real number.

long double x,y;
x=121.09;
y=(long)x;
x=x-(long)x;

Y becomes 121, x in the debugger appears as 0.08999999 but writing it to console shows 0.09.

Also,

double x;
int y;
x=121.09;
y=x;
x=x-y;

Gives the same results. Why is that? I would need a clean 0.09 as i want to get that as an integer (0.09 -> 9)

How can i get the fractional part of the number without modf?

  • 3
    `Why is that?` because 0.09 is not representable by the hardware. At least not as a float or double. – drescherjm Oct 27 '18 at 16:19
  • 2
    It's because [floating point math is broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken), and the only practical way is to either: A) Use custom fixed-precision math libraries in the first place, or B) Format your floating point value as a string, with the required number of digits after the decimal point, then parse the string yourself. Of course, the end result will be a floating point number, which will still be broken. There is no such thing as "clean 0.09" in computer science. – Sam Varshavchik Oct 27 '18 at 16:20
  • 1
    If you had `12109` to begin with (using decimal fixed point) it would be easy to get a clean 9 from that. – harold Oct 27 '18 at 16:24
  • 3
    I recommend reading [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Jesper Juhl Oct 27 '18 at 16:33
  • Alright, thanks a lot – Mitrut Ceclan Oct 28 '18 at 15:13

0 Answers0