Re: Rounding to a certain number of decimal places
- To: mathgroup at smc.vnet.net
- Subject: [mg119274] Re: Rounding to a certain number of decimal places
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sat, 28 May 2011 07:19:40 -0400 (EDT)
On 5/27/11 at 6:14 AM, adeyoung at 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 at Round[10.8168, .001] Out[5]= 10817/1000 which demonstrates Round actually changes the value. But you cannot do something similar with NumberForm.