Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to define a function $f(x)$ such that $f(1.5)=1.5$, $f(1.)=1$, $f(0.)=0$, etc.? Namely, if $x$ is an integer with a decimal point, $f(x)$ returns the integer only, otherwise returns $x$.

This will be useful in the labels of the following plots.

Table[Block[{a = aa}, Show[Plot[x^a, {x, 0, 1}, PlotLabel -> Style[Row@{"a", "=", aa}, 15]]]], {aa, 0, 2, 0.5}]
share|improve this question
I actually just figured out an answer: f[x_] := If[Abs[FractionalPart[x]] < $MachineEpsilon, IntegerPart[x], x] – renphysics Apr 12 '14 at 13:02
f[x_] := If[FractionalPart[x] == 0, IntegerPart[x], x] – renphysics Apr 12 '14 at 13:12
up vote 3 down vote accepted

There are numerous ways to accomplish what you're asking, but here's another way using a single definition:

share|improve this answer

I think the following definitions (you need both) will do want you're asking:

f[x_] := IntegerPart[x] /; x == IntegerPart[x]

f[x_] := x

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.