Tabulating E-format numbers

Discussions related to network, internet and socket programming; also to serial, parallel, Bluetooth, USB etc.
Hated Moron

Tabulating E-format numbers

Post by Hated Moron »

By default, BBC BASIC right-justifies numbers when PRINTed. This generally makes sense, because with integers - and F-format decimal numbers (with a fixed number of decimal places) - right justification will make them line up correctly, e.g. with units in the rightmost column, tens in the next-to-rightmost column etc:

Code: Select all

   -35.325
     3.571
    -2.826
    34.109
  1802.899
     1.997
    -8.843
  -421.575
However with E-format (engineering notation) numbers right-justification isn't generally sensible because the only variable-length part of the number is the exponent itself. Left-justification is a better choice:

Code: Select all

4.220E122
3.493E60
6.762E-219
3.814E-179
2.690E136
5.095E-266
8.831E-192
8.463E127
The exception is when some of the numbers are negative in which case the minus sign will upset the alignment. What we want is to print a leading space to act as a placeholder for the minus sign. One neat way of doing that is the following:

Code: Select all

      PRINT STRING$(-(n >= 0), " "); n
which gives this:

Code: Select all

-4.806E-104
-2.258E65
 4.799E175
-3.690E-237
 2.278E-124
-1.800E-31
-6.606E251
-3.259E-14
Hated Moron

Re: Tabulating E-format numbers

Post by Hated Moron »

Hated Moron wrote: Mon 05 Feb 2024, 19:40 One neat way of doing that is the following:

Code: Select all

      PRINT STRING$(-(n >= 0), " "); n
The above code can be used in a PRINT statement, when writing to a file, when populating (for example) a List Box or when simply assigning the result to a string variable. In the specific case of a PRINT statement it can be simplified to:

Code: Select all

      PRINT SPC(-(n >= 0)); n
jgharston
Posts: 37
Joined: Thu 05 Apr 2018, 14:08

Re: Tabulating E-format numbers

Post by jgharston »

In a similar vein of non-obvious use of string functions, I've used this construct:
PRINT num;" item";LEFT$("s",num<>1)
to get (English) plurals.