Format a number in scientific format

Previous topic - Next topic

Kitty Hello

This code reformats numbers that are too big to display with an 1Exx notation. The E values are factors of 3 (what we engineers need (kilo, mega, giga / milli, nano, pico).
Also the decimal dot is always at the same place!

Code (glbasic) Select

// Format a number with an E exponent if it's
// too long to be written in clear text.
// number         - the number
// decimal_places - number of digits past the decimal point
// digits         - number of digits (or space) before the decimal point
FUNCTION SciFormat$: number, decimal_places, digits
LOCAL a$
LOCAL exp%=0

LOCAL limit = POW(10, digits-1)
LOCAL ilim  = 1.0 / POW(10, MAX(1, decimal_places-3))

LOCAL sg% = SGN(number)
number=ABS(number)

WHILE number<ilim OR number>=limit OR LEN(a$)=0
IF number >= limit
INC exp, 3
number = number / 1000.0
ELSEIF number < ilim
DEC exp, 3
number = number * 1000.0
ENDIF

LOCAL exp$ = ABS(exp)
IF ABS(exp)<10
exp$="0"+exp$
ENDIF
IF exp<0
exp$="-"+exp$
ELSE
exp$=" "+exp$
ENDIF
IF exp=0 OR number=0
a$ = FORMAT$(digits+decimal_places+1, decimal_places, number) + "    "
ELSE
a$ = FORMAT$(digits+decimal_places+1, decimal_places, number) + "E"+exp$
ENDIF
IF number=0.0 THEN BREAK
WEND

IF sg%<0
RETURN "-"+a$
ELSE
RETURN " "+a$
ENDIF

ENDFUNCTION


BTW: That's why I need this:


[attachment deleted by admin]