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$
1
  • $\begingroup$ Read the docs on N $\endgroup$ Commented Dec 4, 2015 at 18:03

1 Answer 1

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] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.