Format string with PRINT command

Post Reply
User avatar
MarkP
Posts: 71
Joined: Tue Apr 07, 2015 9:32 pm

Format string with PRINT command

Post 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?

User avatar
MarkP
Posts: 71
Joined: Tue Apr 07, 2015 9:32 pm

Re: Format string with PRINT command

Post 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

matt7
Posts: 115
Joined: Sun Jul 12, 2015 5:00 pm
My devices: iPhone
Location: USA

Re: Format string with PRINT command

Post 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.

User avatar
Mr. Kibernetik
Site Admin
Posts: 4786
Joined: Mon Nov 19, 2012 10:16 pm
My devices: iPhone, iPad, MacBook
Location: Russia
Flag: Russia

Re: Format string with PRINT command

Post 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

BobRichards
Posts: 11
Joined: Wed May 13, 2020 1:47 pm
My devices: iPad Pro
Location: New Orleans area, USA
Flag: United States of America

Re: Format string with PRINT command

Post by BobRichards »

In my humble opinion, ingenious and eloquent! Thank you, Mr. Kibernetik.

Post Reply