BookmarkSubscribeRSS Feed

Significant Figures

Started ‎06-10-2018 by
Modified ‎06-10-2018 by
Views 3,132

Hi all, The following code is the significant figures implemented through PROC FCMP. However, if you don't familiar FCMP since there are tiny differences between SAS data step and FCMP, you can easily code in data step or in MACRO form.

 

 

******************************************************************************
  Significant Figure(digit) 
******************************************************************************;
* Function to show a number to its significant figure form which could be 
  widely used for scientific number presentation ;
  
libname my "Your physical location...";

proc fcmp outlib=my.func.format;
  function rndgt(x, sf);
  * Round to the specified digit according to significant figure ;
    if x ~= 0 then out=round(x, 10**(ceil(log10(abs(x))) - sf)); else out=0;
    return(out);
  endsub;
  
  function extsf(x) $30;
  * Extract significant digits from a number ;  
    attrib sfc length=$30;
    if x~=0 then do;
      xc=compress(put(x, best.)); /* Char. of x */
      sfc=prxchange("s/[-\.]//", 2, xc); /* Eliminate . and - */
      sfc=prxchange("s/0*([1-9][0-9]*)/$1/", -1, sfc); /* Eliminate leading 0's */
    end; else sfc=' ';
    return(sfc);
  endsub;
      
  function sigFig(x, sf) $30;
  * Show significant figure result as a Char. ;   
    attrib sfc length=$30;
    attrib out length=$30;
    if x=. then do; out=' '; go to return; end; /* If input is missing */
    xr=rndgt(x, sf); /* Rounding result */
    xrc=compress(put(xr, BEST30.)); /* Char. of xr */
    * Adding trailing 0's ;
    n0=sf - lengthn(extsf(xr)); /* Number of adding 0's */
    if n0 > 0 then do; /* The case we need to add 0's */
      zeros=repeat("0", n0 - 1); /* zeros we add*/
      if index(xrc, ".") then out=cats(xrc, zeros); else 
        out=cats(xrc, ".", zeros); /* For integer, adding decimal point */
    end; else out=xrc;
    return:
    return(out);
  endsub;
  
options cmplib=my.func;

* TEST ;
data one;
  length result $30;
  input x;
  sf=3;
  xr=rndgt(x, sf);
  sig=extsf(x);
  result=sigFig(x, sf);
datalines;
.
-0.007777
0.012
0.01235
0.01234
0.0001
1.1
1.125
100.1
0
;
run;

 

Version history
Last update:
‎06-10-2018 12:18 AM
Updated by:
Obsidian | Level 7
Contributors

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!

Free course: Data Literacy Essentials

Data Literacy is for all, even absolute beginners. Jump on board with this free e-learning  and boost your career prospects.

Get Started

Article Tags