Re: Basic Programing Question


[Prev][Next][Index][Thread]

Re: Basic Programing Question



Hi.

Someone asked - perhaps a couple of days ago - about how to get
the number of decimal places in a number.

This problem has no solution in general. How many decimal digits
are there in the PI-number? Or even in 2/3? The proper answer is
'infinite'.

However in practice we are limited by the number of digits the
calculator is able to deal with internally (e.g. TI-92 has
14-digits precision) and the number of digits it is able to
show on the display (influenced by MODE options).

Therefore for those practical purposes I wrote a function which
takes any numerical expression as its argument and returns
a 3-element list:
- number of digits (including possible minus sign) before the
  decimal point
- number of digits (with all trailing zeros stripped) after the
  decimal point
- the numeric string in a "normalized" form, i.e. instead of
  -.333 it gives -0.333
If the argument is too large (or too small) and requires
exponential notation, the function gives up and returns just
two-element list: {"exp", numeric_string}

Of course the results depend on the current MODE FIX/FLOAT and
NORMAL/SCIENTIFIC/ENGINEERING settings.

The code can be improved. The internal function rtrim is
unnecessarily general and could be simplified for our particular
purposes.

Regards
MJ Wiechowski


\START92\
\COMMENT=Written by MJ Wiechowski 1998-10-06
\NAME=ndigs
\FILE=NDIGS.9XF
(exprs)
Func
  Local  rtrim,s,dp,lft,rgt

\(C)\ Delete trailing spaces and zeros
  Define  rtrim(st)=Func
    Local  c,n
    dim(st)\->\n
    If  n=0   \(C)\ Empty string
      Return  st
    Loop     \(C)\ Non-empty string
      mid(st,n,1)\->\c
      If  c\!=\" " and c\!=\"0"
        Exit
      n-1\->\n
      If  n=0 \(C)\ Nothing left
        Exit
    EndLoop
    Return  left(st,n)
  EndFunc

  string(approx(exprs))\->\s
  \(C)\ We give up if exponent is present
  If  inString(s,"\ee\")>0
    Return  {"exp", s}

  \(C)\ No exponent present
  rtrim(s)\->\s
  \(C)\ Normalization
  If left(s,1)="." Then
    "0"&s\->\s: 2\->\dp
  ElseIf left(s,2)="\(-)\." Then
    "\(-)\0."&mid(s,3)\->\s: 3\->\dp
  Else
    inString(s,".")\->\dp
  EndIf

  dp-1\->\lft
  dim(s)-dp\->\rgt
  Return  {lft,rgt,s}
EndFunc

\STOP92\


References: