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?
Format string with PRINT command
Re: Format string with PRINT command
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
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
Here's another option that builds the format string from right to left and then applies it.
Add a trim$() to the return line or whenever you call fmt$ to remove leading spaces.
Code: Select all
def fmt$(a)
f$="###"
m=1000
while abs(a)>=m
f$="###,"&f$
m*=1000
endwhile
return str$(a,f$)
enddef
- Mr. Kibernetik
- Site Admin
- Posts: 4786
- Joined: Mon Nov 19, 2012 10:16 pm
- My devices: iPhone, iPad, MacBook
- Location: Russia
- Flag:
Re: Format string with PRINT command
Ok, my version:
outputs:
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
Code: Select all
123
1,234
-
- Posts: 11
- Joined: Wed May 13, 2020 1:47 pm
- My devices: iPad Pro
- Location: New Orleans area, USA
- Flag:
Re: Format string with PRINT command
In my humble opinion, ingenious and eloquent! Thank you, Mr. Kibernetik.