l can't get the 'exact' decimal part of a float number

Hi all, l have a serious issue here.

lm trying to get the decimal part of a float number; then l want to transform that decimal into an integer.

The issue is when l get the 0.86, and when l print that value, the program outputs this: 0.859985

l'll explain what l do:
1
2
3
4
5
6
7
8
9
  float salary, res;

  salary = 286.86;
  // so to get the decimal part of salary, my idea was: 286.86 - 286 = 0.86
  res = salary - trunc (salary);
  printf ("%f", res); // outputs 0.859985 instead of 0.86
  
  // finally l wanna make that decimal to become an integer (supposing l got 0.86)
  res = res * 100;


By the way, in my math library the truncate funcion is not implemented. so l wrote the following trunc function within my library:
 
  double trunc(double d){ return (d>0) ? floor(d) : ceil(d) ; };


l dont think this question is in another post, so l decided to ask here.
lm using c++ borland builder 6, lm on a console application project. my system is windows xp, sp3 ,32 bit. Thanks for anticipated.
Hello vincentthorpe,

Try printf ("%0.2f", res);.

You might want to look at this page:
http://www.cplusplus.com/reference/cstdio/printf/?kw=printf

Hope that helps,

Andy
Floating point numbers cannot exactly represent 286.86

There's an enormous range of values it cannot exactly represent. The closest you can get with a 32 bit floating point value in IEEE-754 floating point is:

01000011100011110110111000010100

which represents 286.8599853515625


The next value, 01000011100011110110111000010101, represents 286.860015869140625

As Handy suggests, you can have the value rounded to two decimal places for output, and there are various things you can do to round it, but a floating point value cannot exactly represent 286.86 - when you tried to set the value of salary to 286.86, that's not what you got.

Here's somewhere you can experiment; https://www.h-schmidt.net/FloatConverter/IEEE754.html
Last edited on
you can use integers for this, with a great deal of effort to compute and manage the data.
you can also use higher precision floating point; many systems support 80 bit floats and a few support up to 128 bit if memory serves. Those get you closer, but you always have the same problem.

To state it concisely, it can be proven easily that there are more values between 0 and 1 than there are whole/counting numbers. Simply take the reciprocal of all the whole numbers and fill in the gaps to see this.

The problem is the same. You have a finite # of bits to represent ALL values in the universe. You simply can't have a distinct value for each one, the best you can do is approximate them and even with approximation there are still max min limits to boot.


Topic archived. No new replies allowed.