### Author Topic: Format a number in scientific format  (Read 2187 times)

#### Kitty Hello

• code monkey
• Prof. Inline
•       • • Posts: 10725
• here on my island the sea says 'hello' ##### Format a number in scientific format
« on: 2010-Apr-22 »
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 pointFUNCTION SciFormat\$: number, decimal_places, digitsLOCAL a\$LOCAL exp%=0LOCAL 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\$ ENDIFENDFUNCTION`
BTW: That's why I need this: