5

There is some kind of function for the printf function in which you can use %g, which will show the whole number 3 if the float is 3.00 and will show 3.01 if it's actually a float, is there any way you can do this through some code?

Drew Dormann
  • 54,920
  • 13
  • 119
  • 171
user2140285
  • 155
  • 2
  • 3
  • 12

1 Answers1

8

There isn't really a simple answer

Integral values do have exact representations in the float and double formats. So, if it's really already integral, you can use:

f == floor(f)

However, if your value is the result of a calculation which at one point involved any sort of non-zero fractional part, then you will need to be concerned that you may have something very close to an integer but which isn't really, exactly, to-the-last-bit the same. You probably want to consider that to be integral.

One way this might be done:

fabs(f - round(f)) < 0.000001

And while we are on the subject, for the purists, we should note that int i = f; or double i = f; will round according to the FPU mode whereas round(3) will round half-way cases away from zero.

DigitalRoss
  • 139,415
  • 24
  • 238
  • 326
  • 1
    Thanks, this looks very useful. – user2140285 Mar 09 '13 at 17:50
  • 1
    @user2140285 - be careful. "Nearly equal" is an advanced technique. It violates transitivity (a nearly equals b and b nearly equals c does not mean that a nearly equals c) and it can mask real problems that will bite you later. – Pete Becker Mar 09 '13 at 18:05
  • 1
    You may find the constants `FLT_EPSILON`, `DBL_EPSILON`, and `LDBL_EPSILON` (defined in ``) handy for comparison when using this technique – fish2000 Apr 21 '16 at 20:28
  • Good advice here from Pete Becker and fish2000. It is an advanced technique. (And why I said: *no simple answer* here.) – DigitalRoss Sep 06 '16 at 18:46
  • "Integral values do have exact representations in the float and double formats" - maybe this text need some correction (just to improved). double and float in real computers which used general model ISO/IEE 754-1985 use finite number of bits for mantissa. Just look into FLT_MANT_DIG(24) and DBL_MANT_DIG(53). So it can be said that if you have 24-bits integer or 53-bits integer then representation is the same. – Konstantin Burlachenko Aug 31 '17 at 11:31