Take the 2-minute tour ×

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?

share|improve this question
is what %g is I think, I am not sure what did you ask –  Grijesh Chauhan Mar 9 '13 at 17:42
Can you please restate the question? I don't understand what you're asking. –  Praetorian Mar 9 '13 at 17:42
the function of %g but then in an actual function so I can use it outside of printf. –  user2140285 Mar 9 '13 at 17:49

2 Answers 2

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.

share|improve this answer
Thanks, this looks very useful. –  user2140285 Mar 9 '13 at 17:50
@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 9 '13 at 18:05

Try double modf( double, double * ) function. [http://www.codecogs.com/reference/computing/c/math.h/modf.php][1]

share|improve this answer

Your Answer


