Older Version Newer Version

GrahameKing GrahameKing Aug 23, 2006

The following code demonstrates one way of converting any number to standard scientific notation. This code is from newsletter 139, posted here by the author. [[code]] ' test program for scientific notation function by Grahame King - released to public domain August 2006 a=1 while a<>0 input "test number ="; a a$ = str$(a) print "test number as string = "+a$ print "test number in scientific notation = "+ScNotation$(a) wend end function ScNotation$(numin) ' function to express a number as a string in 'scientific notation" if numin = 0 then ScNotation$ = "0" : exit function ' separate number into sign, significant numeric part (mantissa), and exponent ' first extract the sign absNumIn = abs(numin) sgnNumIn = absNumIn/numin if sgnNumIn>0 then sgnNumIn$ = "" else sgnNumIn$ = "-" end if ' represent unsigned number as a string using str$ absNumIn$ = str$(absNumIn) ' find the "e" in case LB has already put it in a form with an exponent inde = instr(absNumIn$,"e") if inde>0 then expon = val(mid$(absNumIn$,inde+1)) mantissa$ = mid$(absNumIn$,1,inde-1) else expon = 0 mantissa$ = absNumIn$ end if ' move the decimal point in the old mantissa so that there is just one nonzero digit in front of it ' and adjust the exponent accordingly ' start by finding the decimal point and breaking mantissa into its whole part and fractional part indDot = instr(mantissa$,".") if indDot = 0 then ' for integers indDot = len(mantissa$) whole$ = mantissa$ fract$ = "" else whole$ = mid$(mantissa$,1,indDot-1) fract$ = mid$(mantissa$,indDot+1) end if while val(whole$) > 9 ' to move decimal point to the left if necessary indDot = indDot-1 fract$ = right$(whole$,1)+fract$ ' add the last digit from the whole number part to the beginning of fract$ whole$ = left$(whole$,len(whole$)-1) ' and then remove that digit from the whole$ expon = expon+1 ' adjust exponent to keep the net result correct wend while val(whole$) <= 0 ' to move decimal point to the right if necessary indDot = indDot+1 whole$ = whole$+left$(fract$,1) ' add the first digit of fractional part to the whole number part fract$ = mid$(fract$,2) ' and then remove that digit from the beginning of the fractional part expon = expon-1 ' adjust exponent to keep the net result correct wend ' build Scientific Notation string from the three parts - sign, new mantissa and new exponent ScNotation$ = sgnNumIn$+str$(val(whole$))+"."+fract$+"e"+str$(expon) end function [[code]]