function roundoff,val_inp,ndec,str=str ;+ ; ; Roundoff: A function that rounds a figure to a specified ; number of decimal points, limited to 18 significant ; figures. The function adds trailing zeroes if the ; requested number of decimal points is more than the ; precision of the input figure. ; ; Syntax: ; Result = ROUNDOFF(VAL, NDEC [, /STR]) ; ; Inputs: ; VAL - the number to be rounded ; NDEC - the desired number of decimal points ; ; Keyword: ; STR - Set /str to return a string. Default returns float. ; ; Katie Peek / Mar 2008 ; / Jan 2009: Added proper treatment of very large & ; very small numbers. ; ;- if (n_elements(val_inp) eq 0) then begin print,' Result = roundoff(val_inp, ndec, /str)' print,' Enter negative value for ndec to round to left of decimal.' print,' Routine can only handle 18 significant figures.' return,'' end ; Protect input. val=double(val_inp) ; Confirm that the rounding won't break. if (floor(alog10(val)) + ndec gt 18) then begin message,' This routine can only handle 18 significant figures.' endif ; Do the rounding. valbig = (10.^ndec) * val ; multiply valround = round(valbig,/l64) ; round valout = valround/(10.d^ndec) ; divide ; Special treatment for the scientific notation case (sux). if strhas(str(valout),'e') then begin pwr = fix((strsplit(str(valout),'e',/ext))[1]) ; extract power num = (strsplit(str(valout),'e',/ext))[0] ; extract coeff num = strsplit(num,'.',/ext) num = num[0]+num[1] if (pwr lt 0) then begin ; Negative exponent case. valout = '0.' for i=0,abs(pwr)-2 do valout=valout+'0' ; Add leading zeroes. valout = valout+num ; Tack on coefficient. if strlen((strsplit(valout,'.',/ext))[1]) lt ndec then begin message,' Double-precision value required.' endif endif else begin ; Positive exponent case. valout = num ; Start with coefficient. while (strlen(valout) gt pwr) do begin valout = str(round(double(valout)/10.)) endwhile while (strlen(valout) lt pwr) do begin valout = valout+'0' ; Add zeroes before decimal if necessary. endwhile valout = valout+'.0' ; Add decimal. endelse endif ; String valout may now be treated as non-scientific notation. ; String treatment. if keyword_set(str) then begin ; Make it a string. valout = str(valout) ; Add zeroes after decimal if necessary. while (strlen((strsplit(valout,'.',/ext))[1]) lt ndec) do begin valout = valout+'0' endwhile ; Make string appropriate length. decpos = strpos(str(valout),'.') valout = strmid(str(valout),0,decpos+ndec+1) ; If valout ends in decimal, remove that decimal. if (strmid(valout,0,/rev) eq '.') then begin valout = strmid(valout,0,strlen(valout)-1) endif endif else begin ; Un-stringify if /str not set. if (size(valout,/type) eq 7) then valout = double(valout) endelse return,valout end