How do I set up a function's options so that the function returns its results in either the exact form (default) or with N decimal places?
1 Answer
fun[x_, r_Integer: 0] :=
x + 1 // If[r == 0, #, N[#, Length@IntegerDigits@IntegerPart@# + r]] &
fun[1]
2
fun[1, 4]
2.0000
fun[1/2]
3/2
fun[1/2, 1]
1.5
If you need this also for other functions you could define
rounder[x_, 0] := x
rounder[x_, r_] := N[x, Length@IntegerDigits@IntegerPart@x + r]
and now simply
foo[x_, r_Integer: 0] := rounder[x + 2, r]
N
$\endgroup$