Page 1 of 1

Format string with PRINT command

Posted: Fri Jan 15, 2021 8:55 pm
by MarkP
The format string with the print command can be very useful when formatting numbers.

However, when formatting large numbers using the comma for thousands, millions, and billions separator character, the following occurs:

a=1234567
print "###,###,###":a
' yields: 1,234,567

a=672
print "###,###,###":a
' yields: , ,672

Is there an easy way to format this correctly? That is, a way to eliminate the leading commas?

Re: Format string with PRINT command

Posted: Fri Jan 15, 2021 11:57 pm
by MarkP
Unless there's a better way by simply using the format string, this is what I got:

print fmt$(123456789)
print fmt$(1234)
print fmt$(45)
print fmt$(123456789012)
end

def fmt$(a)
f$=str$(a,"###,###,###,###")
while instr(f$," ,")>0
L=instr(f$," ,")
f$=mid$(f$,L+2)
endwhile
return f$
enddef

Re: Format string with PRINT command

Posted: Sat Jan 16, 2021 3:29 pm
by matt7
Here's another option that builds the format string from right to left and then applies it.

Code: Select all

def fmt$(a)
f$="###"
m=1000
while abs(a)>=m
f$="###,"&f$
m*=1000
endwhile
return str$(a,f$)
enddef
Add a trim$() to the return line or whenever you call fmt$ to remove leading spaces.

Re: Format string with PRINT command

Posted: Sat Jan 16, 2021 3:48 pm
by Mr. Kibernetik
Ok, my version:

Code: Select all

def fmt$(x)=right$("###,###,###",floor(log10(x)/3)*4+1)

a=123
b=1234

print fmt$(a):a
print fmt$(b):b
outputs:

Code: Select all

123
1,234

Re: Format string with PRINT command

Posted: Thu Feb 25, 2021 5:51 pm
by BobRichards
In my humble opinion, ingenious and eloquent! Thank you, Mr. Kibernetik.