Tip: Print Using

Share your advanced PureBasic knowledge/code with the community.
PB
PureBasic Expert
PureBasic Expert
Posts: 7581
Joined: Fri Apr 25, 2003 5:24 pm

Tip: Print Using

Post by PB »

Here's my (simple) version of Print Using to format numbers. I say simple because
it's not fully tested and can be enhanced further, but it does the job that I need.

If Fred/Freak is reading, I would like to take this opportunity to ask for something
like this to become a native command, just like in other Basics. :)

Code: Select all

; Print Using example by PB. Free for any use. :)

; Usage: string$=Using(number,format$)
; string$ = "" if number can't be formatted.
; Only one format$ per call (see multiple example).

; format$ can contain these characters:
;  # = next digit in number, or nothing if no next digit.
;  0 = next digit in number, or Chr(48) if no next digit.
;  _ = next digit in number, or space if no next digit.

Procedure.s Using(number,format$)
  n$=Str(number) : d=Len(n$)+1
  f=CountString(format$,"#")+CountString(format$,"0")+CountString(format$,"_")
  If d-1<f+1 ; Number fits into format$, so do it.
    For p=Len(format$) To 1 Step -1
      c$=Mid(format$,p,1)
      Select c$
        Case "#" : d-1 : If d<1 : d$="" : Else : d$=Mid(n$,d,1) : EndIf
        Case "0" : d-1 : If d<1 : d$="0" : Else : d$=Mid(n$,d,1) : EndIf
        Case "_" : d-1 : If d<1 : d$=" " : Else : d$=Mid(n$,d,1) : EndIf
        Default : d$=c$
      EndSelect
      t$+d$
    Next
    For p=Len(t$) To 1 Step -1 : u$+Mid(t$,p,1) : Next
  EndIf
  ProcedureReturn u$
EndProcedure

num=123
Debug "Number = "+Str(num)
Debug Using(num,"With hash = #####") ; Returns "With hash = 123"
Debug Using(num,"With zero = 0,000") ; Returns "With zero = 0,123"
Debug Using(num,"With line = $____") ; Returns "With line = $ 123"
Debug Using(num,"Multiple  = 0000000 and ")+Using(num,"$#######")
I compile using 5.31 (x86) on Win 7 Ultimate (64-bit).
"PureBasic won't be object oriented, period" - Fred.