Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #2760 > unrolled thread
| Started by | Bill Rowe <readnews@sbcglobal.net> |
|---|---|
| First post | 2011-05-28 11:19 +0000 |
| Last post | 2011-05-28 11:19 +0000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.soft-sys.math.mathematica
Re: Rounding to a certain number of decimal places Bill Rowe <readnews@sbcglobal.net> - 2011-05-28 11:19 +0000
| From | Bill Rowe <readnews@sbcglobal.net> |
|---|---|
| Date | 2011-05-28 11:19 +0000 |
| Subject | Re: Rounding to a certain number of decimal places |
| Message-ID | <irqlog$e8b$1@smc.vnet.net> |
On 5/27/11 at 6:14 AM, adeyoung@andrew.cmu.edu (Andrew DeYoung)
wrote:
>I would like to be able to round a number to a certain, specified
>number of decimal places (not number of digits), including zeros.
>Suppose that some function f does this, and takes two arguments, the
>number to be rounded and the number of decimal places to which to
>round: f[number, numPlaces]. Then, for example, I would like the
>following results, if possible:
>f[0.8168, 3] = 0.817
>f[1.8168, 3] = 1.817
>f[10.8168, 3] = 10.817
>f[100.8168, 3] = 100.817
>f[0.99, 3] = 0.990
>f[0.9, 3] = 0.900
>f[0.00572, 3] = 0.006
>Is there a function f (either built-in or a custom function) that
>can do this?
Except for .99 and .9 the answer is yes. Round will do what you
want. Specifically,
In[1]:= Round[{0.8168, 1.8168, 10.8168, 100.8168, 0.99, 0.9,
0.00572}, .001]
Out[1]= {0.817,1.817,10.817,100.817,0.99,0.9,0.006}
or if you prefer to specify the number of places past the
decimal point
f[x_, n_] := Round[x, 10^-n]
>Mathmatica's built-in function NumberForm does not
>quite do this because the user specifies the number of digits, not
>the number of decimal places. Also, NumberForm does not count zeros
>after the decimal point as digits, nor does it add extra zeros as
>needed if they are redundant.
Actually, NumberForm can be used. For example,
In[3]:= NumberForm[.9, {1, 3}]
Out[3]//NumberForm= 0.900
or
In[4]:= NumberForm[10.8168, {5, 3}]
Out[4]//NumberForm= 10.817
In fact for the case of .9 and .99 you have to use something
like NumberForm since Mathematica will not display trailing
zeros for any function that returns a number.
Note, there is a key difference between Round[x,.001] and
NumberForm[x,{n,3}]. Round outputs a value that is different
from the starting value that can be used in subsequent
computation. NumberForm controls the display of the value by
putting a wrapper around the expression being evaluated. The
point is you can do something like
In[5]:= Rationalize@Round[10.8168, .001]
Out[5]= 10817/1000
which demonstrates Round actually changes the value. But you
cannot do something similar with NumberForm.
Back to top | Article view | comp.soft-sys.math.mathematica
csiph-web