1
$\begingroup$

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?

$\endgroup$
2
$\begingroup$
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]
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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