'===========================================================================
' Subject: Rounding off Decimals              Date: 09-15-02 (  :  )       
'  Author: David Williams                     Code: Qbasic,QB,PDS          
'  Origin: david.williams@ablelink.org      Packet: ALGOR.ABC
'===========================================================================
' ROFFDEM.BAS 
' David Williams. 2002 
  
' david.williams@ablelink.org 
  
' This program contains and demonstrates a FUNCTION that produces 
' a string that shows a rounded-off representation of a decimal 
' number. The function takes two arguments, a real number that 
' is to be rounded, and an integer which shows the required number 
' of decimal places. The integer is allowed to be positive or 
' negative. Its sign is a flag as to whether or not trailing zeroes 
' to the right of the decimal point should be truncated. The absolute 
' value of the integer is the number of decimal places. 
  
' If there is no other digit to the left of the decimal point, a zero 
' is placed there. If truncation leaves no digits to the right of the 
' decimal point, the point itself is omitted. No spaces are added to 
' the left or right of the number. 
  
DECLARE FUNCTION ROff$ (N!, P%) 
DO 
  INPUT "Number to be rounded (or ENTER to quit)"; N$ 
  IF N$ = "" THEN EXIT DO 
  N = VAL(N$) 
  INPUT "How many places of decimals"; P% 
  P% = ABS(P%)  ' ensure number is positive 
  INPUT "Trim trailing zeroes (Y/n)"; T$ 
  IF UCASE$(LEFT$(T$, 1)) = "N" THEN P% = -P% 
  ' negative P% flags non-trimming of zeroes 
  Q$ = CHR$(34)  ' quotation mark 
  PRINT "String showing rounded number is: "; Q$; ROff$(N, P%); Q$ 
  PRINT "(Quotation marks are not included in string.)" 
  PRINT 
LOOP 
END 
  
FUNCTION ROff$ (N, P%) 
' Produces string that shows N rounded off to ABS(P%) places of 
' decimals. Sign of P% shows whether trailing zeroes are truncated. 
  F% = ABS(P%) 
  H& = INT(10 ^ F% * N + .5) 
  IF H& < 0 THEN M$ = "-" ELSE M$ = "" 
  S$ = LTRIM$(STR$(ABS(H&))) 
  L% = LEN(S$) 
  IF L% < F% + 1 THEN 
    S$ = STRING$(F% + 1 - L%, "0") + S$ 
    L% = F% + 1 
  END IF 
  T$ = "." + RIGHT$(S$, F%) 
  IF P% >= 0 THEN 
    DO WHILE RIGHT$(T$, 1) = "0" 
      T$ = LEFT$(T$, LEN(T$) - 1) 
    LOOP 
    IF T$ = "." THEN T$ = "" 
  END IF 
  ROff$ = M$ + LEFT$(S$, L% - F%) + T$ 
END FUNCTION 
  
