BookmarkSubscribeRSS Feed

Significant Figures

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

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;

 

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

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

SAS AI and Machine Learning Courses

The rapid growth of AI technologies is driving an AI skills gap and demand for AI talent. Ready to grow your AI literacy? SAS offers free ways to get started for beginners, business leaders, and analytics professionals of all skill levels. Your future self will thank you.

Get started

Article Tags